diff --git a/app.js b/app.js index d9ba075..dc74478 100644 --- a/app.js +++ b/app.js @@ -23,6 +23,13 @@ import { findMissingCodeFiles, } from "./src/flutterFlowCodeFileProvisioning.js"; import { buildReviewPresentation } from "./src/reviewPresentation.js"; +import { + expectedWidgetClassFromFileName, + findUnbalancedBracketError, + getDeclaredWidgetClasses, + sanitizeGeneratedDart, + widgetFileNameForClass, +} from "./src/flutterFlowCodeSanitizer.js"; import { formatFlutterFlowFileError } from "./src/flutterFlowFileErrors.js"; import { extractPackageImports } from "./src/dartPackageImports.js"; import { readProvisionResponse } from "./src/provisionStream.js"; @@ -1447,6 +1454,12 @@ function getCurrentArtifactMetadata() { return { artifactType: artifact.artifactType || "CustomWidget", artifactName: artifact.artifactName || "GeneratedWidget", + // Single-file deploys must name the committed file after the artifact's + // own validated fileName (FF naively snake_cases the declared class), not + // a fresh name derived from artifactName. The bundle planner already uses + // artifact.fileName; the single-file path was dropping it, so FF saw a + // file named after the artifact name and found no matching widget class. + fileName: artifact.fileName || "", }; } @@ -1498,6 +1511,24 @@ const FF_API_ENDPOINTS = { staging: "https://api.flutterflow.io/v2-staging/", }; +/** + * Builds the actionable error shown when listing projects is denied. Both + * callers surface this text verbatim in their dropdowns, and re-entering a key + * in API Keys settings is the app's re-auth path for static FlutterFlow keys. + * @param {number} status - HTTP status from listProjects + * @param {string} errorText - Server-provided detail, truncated for display + * @returns {string} User-facing message naming the fix + */ +function buildListProjectsAuthError(status, errorText) { + const detail = errorText?.trim() + ? ` (${errorText.trim().slice(0, 200)})` + : ""; + if (status === 401) { + return `Your FlutterFlow API key was rejected (401 Unauthorized)${detail}. Re-enter a current key under API Keys settings, then try again.`; + } + return `Listing FlutterFlow projects was denied (403)${detail}. The key may be scoped to sync a single project without list permission - verify the key's access in FlutterFlow, re-enter it under API Keys settings, then retry.`; +} + /** * Client for interacting with the FlutterFlow API. * Adapted from the VS Code extension for browser use. @@ -1744,72 +1775,88 @@ class FlutterFlowApiClient { } /** - * Lists projects accessible with the current API key. - * @param {Object} [options] - Optional parameters - * @param {number} [options.page] - Page number for pagination - * @param {number} [options.limit] - Maximum number of projects per page - * @returns {Promise>} Array of project objects with id and name + * Parses a successful listProjects payload. Handles FlutterFlow's wrapper + * format ({ success: true, value: "" }) plus looser + * shapes older deployments return. + * @param {Object} data - Parsed JSON body + * @returns {Array} Projects as { id, name } */ - async listProjects(options = {}) { - const { page = 1, limit = 100 } = options; - console.log(`Listing projects for API key via V2 endpoint`); + parseProjectsResponse(data) { + if (data?.success && typeof data.value === "string") { + try { + const parsedValue = JSON.parse(data.value); + if (parsedValue && Array.isArray(parsedValue.entries)) { + return parsedValue.entries.map((entry) => ({ + id: entry.id, + name: entry.project?.name || entry.id, + })); + } + } catch (parseError) { + console.error("Failed to parse stringified project value:", parseError); + } + } - try { - const response = 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: true, - }), - }, - ); + const projects = + data?.projects || data?.items || data?.entries + || (Array.isArray(data) ? data : []); + return Array.isArray(projects) ? projects : []; + } - if (!response.ok) { - const errorText = await response.text(); - throw new Error( - `List projects failed: ${response.status} - ${errorText}`, - ); - } + async listProjects() { + console.log("Listing projects for API key"); - const data = await response.json(); + // Every other call in this client targets `${baseUrl}`; this one + // alone hardcoded a legacy `/v2/l/` path that the gateway rejects with + // 401/403 before the key is evaluated, surfacing as "List projects failed: + // 403 Unauthorized" while sync calls with the same key worked. The + // convention path goes first; the legacy path is retried once on 404 only, + // so an auth rejection is never masked by a retry. + const attemptUrls = [ + `${this.baseUrl}listProjects`, + "https://api.flutterflow.io/v2/l/listProjects", + ]; + let lastStatus = 0; + let lastErrorText = ""; + + for (const url of attemptUrls) { + const response = await fetch(url, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${this.apiKey}`, + }, + body: JSON.stringify({ + project_type: "ALL", + deserialize_response: true, + }), + }); - // Handle the specific FlutterFlow API wrapper format: - // { success: true, value: "{\"entries\": [...]}" } - if (data.success && typeof data.value === "string") { - try { - const parsedValue = JSON.parse(data.value); - if (parsedValue && Array.isArray(parsedValue.entries)) { - // Map to standard format: { id, name } - return parsedValue.entries.map((entry) => ({ - id: entry.id, - name: entry.project?.name || entry.id, - })); - } - } catch (parseError) { - console.error( - "Failed to parse stringified project value:", - parseError, - ); + if (response.ok) { + if (url !== attemptUrls[0]) { + console.log(`listProjects answered on legacy path ${url}`); } + return this.parseProjectsResponse(await response.json()); } - // Fallback for other potential formats - const projects = - data.projects || - data.items || - data.entries || - (Array.isArray(data) ? data : []); - return Array.isArray(projects) ? projects : []; - } catch (error) { - console.error("Error listing projects:", error); - throw error; + lastStatus = response.status; + lastErrorText = await response.text(); + console.warn( + `listProjects via ${url} returned ${lastStatus}: ${lastErrorText}`, + ); + + // 401 means the key itself is invalid/expired; 403 usually means the key + // is valid but scoped to sync a single project without list permission. + // Either way the user must act in API Keys settings, so fail with that + // instruction instead of a raw status line. + if (response.status === 401 || response.status === 403) { + throw new Error(buildListProjectsAuthError(response.status, lastErrorText)); + } + if (response.status !== 404) { + throw new Error(`List projects failed: ${response.status} - ${lastErrorText}`); + } } + + throw new Error(`List projects failed: ${lastStatus} - ${lastErrorText}`); } } @@ -1866,8 +1913,20 @@ async function parsePushCodeResponse(response) { }; } - // Success response - const valueObject = jsonResult.value ? JSON.parse(jsonResult.value) : {}; + // Success response. The value payload carries per-file warnings; a malformed + // or non-string value must not fail the whole commit - the push itself + // already succeeded (HTTP ok), so degrade to "no warnings" instead. + let valueObject = {}; + if (jsonResult.value) { + try { + valueObject = + typeof jsonResult.value === "string" + ? JSON.parse(jsonResult.value) + : jsonResult.value; + } catch (parseError) { + console.warn("Ignoring malformed push response value:", parseError); + } + } return { success: true, responseCode: response.status, @@ -2226,6 +2285,37 @@ function runPreCommitChecks(codeInfo) { ); } + // FlutterFlow formats every pushed file with dart_style, which fails on + // unbalanced brackets with the opaque "Custom widget code is not + // formattable". Catch it here, where the message can say exactly what and + // where is wrong, instead of after a round-trip to FF. + const unbalancedBrackets = findUnbalancedBracketError(codeInfo.content); + if (unbalancedBrackets) { + issues.push( + `FlutterFlow cannot format this code - ${unbalancedBrackets}. Fix or regenerate before committing.`, + ); + } + + // A CustomWidget is committed under a file name FlutterFlow reads the widget + // identity back out of. If the code declares no public widget class, or the + // declared class cannot be recovered from the file name, FlutterFlow rejects + // the push with "Custom widget code is not formattable" / "No widget + // found". Catch that here instead of after a round-trip to FF. + if (codeInfo.codeType === CodeType.WIDGET) { + const declared = getDeclaredWidgetClasses(codeInfo.content); + const expectedFromFile = expectedWidgetClassFromFileName(codeInfo.fileName); + if (declared.length === 0) { + issues.push( + "No public widget class found (must extend StatelessWidget or StatefulWidget).", + ); + } else if (!declared.includes(expectedFromFile)) { + const expected = `${widgetFileNameForClass(declared[0])}`; + issues.push( + `Widget class name "${declared[0]}" does not match the file name "${codeInfo.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${expectedFromFile} found". Rename the file to "${expected}" or the class to match before committing.`, + ); + } + } + return { canProceed: issues.length === 0, issues, @@ -2244,26 +2334,41 @@ function runPreCommitChecks(codeInfo) { * @returns {Object} Prepared code info { content: string, fileName: string, codeType: string } */ function prepareCodeForCommit(rawCode, options = {}) { - const { artifactType = "CustomWidget", artifactName = "GeneratedCode" } = - options; - - // Clean up the code - let cleanedCode = rawCode.trim(); - - // Remove markdown code fences if present - if (cleanedCode.startsWith("```dart")) { - cleanedCode = cleanedCode.replace(/^```dart\n/, ""); - } else if (cleanedCode.startsWith("```")) { - cleanedCode = cleanedCode.replace(/^```\n/, ""); - } - - if (cleanedCode.endsWith("```")) { - cleanedCode = cleanedCode.replace(/\n```$/, ""); - } - - // Ensure proper class/function naming - let fileName = artifactName; - if (!fileName.endsWith(".dart")) { + const { + artifactType = "CustomWidget", + artifactName = "GeneratedCode", + fileName: providedFileName, + } = options; + + // Strip BOM, markdown code fences, and blank padding. LLM responses arrive + // wrapped in fences often enough that leaving them in guarantees FlutterFlow + // rejects the push as "not formattable". + const cleanedCode = sanitizeGeneratedDart(rawCode); + + // FF derives a widget's identity from the committed file name, so a widget + // must land under the FF naive snake_case of the class the code actually + // declares - not under the artifact's display name ("Liquid Glass Orbs" + // becomes a file FF cannot resolve to any widget). Any other name - even one + // that merely capitalizes differently - makes FF report "No widget + // found", so a declared class always wins and the file is renamed (and + // logged) to match. CustomFunction always lands in custom_functions.dart. + let fileName = providedFileName || artifactName; + if (artifactType === "CustomFunction") { + fileName = "custom_functions.dart"; + } else if (artifactType === "CustomWidget") { + const declaredClass = getDeclaredWidgetClasses(cleanedCode)[0]; + const canonicalName = declaredClass + ? widgetFileNameForClass(declaredClass) + : null; + if (canonicalName && fileName !== canonicalName) { + console.warn( + `Commit file name "${fileName}" does not match declared widget class "${declaredClass}"; renaming to "${canonicalName}" so FlutterFlow can find the widget.`, + ); + fileName = canonicalName; + } else if (!fileName.endsWith(".dart")) { + fileName += ".dart"; + } + } else if (!fileName.endsWith(".dart")) { fileName += ".dart"; } @@ -2278,7 +2383,6 @@ function prepareCodeForCommit(rawCode, options = {}) { break; case "CustomFunction": codeType = CodeType.FUNCTION; - fileName = "custom_functions.dart"; break; case "CustomClass": case "CodeFile": @@ -2756,34 +2860,32 @@ async function commitToFlutterFlow(dartCode, fileName, options = {}) { */ async function createZipFromFileMap(fileMap) { - try { - const zip = new JSZip(); - - for (const [name, info] of fileMap.entries()) { - zip.file(name, info.content); - } + // No error swallowing here: a failed zip used to return "" and the push + // would send an empty archive, turning a local packaging bug into an opaque + // FlutterFlow rejection. Every caller already runs inside a try/catch that + // surfaces the failure, so let the error propagate with its real cause. + const zip = new JSZip(); - const zipBuffer = await zip.generateAsync({ - type: "base64", - compression: "DEFLATE", - compressionOptions: { level: 6 }, - }); - return zipBuffer; - } catch (error) { - console.error("Error creating zip:", error); - return ""; + for (const [name, info] of fileMap.entries()) { + zip.file(name, info.content); } + + return zip.generateAsync({ + type: "base64", + compression: "DEFLATE", + compressionOptions: { level: 6 }, + }); } async function executeCommit(code, options = {}) { - const { artifactType, artifactName, pipelineResult } = options; + const { artifactType, artifactName, fileName, pipelineResult } = options; console.log(`Starting commit for ${artifactName} (${artifactType})`); try { // Step 1: Prepare the code commitState.setState(CommitState.PREPARING); - const codeInfo = prepareCodeForCommit(code, { artifactType, artifactName }); + const codeInfo = prepareCodeForCommit(code, { artifactType, artifactName, fileName }); // Step 2: Extract dependencies const deps = extractDependencies(codeInfo.content); @@ -3752,9 +3854,9 @@ async function initiateCommitToFlutterFlow() { return; } - const { artifactType, artifactName } = getCurrentArtifactMetadata(); + const { artifactType, artifactName, fileName } = getCurrentArtifactMetadata(); - const codeInfo = prepareCodeForCommit(code, { artifactType, artifactName }); + const codeInfo = prepareCodeForCommit(code, { artifactType, artifactName, fileName }); const checks = runPreCommitChecks(codeInfo); @@ -5439,7 +5541,11 @@ async function confirmCommitToFlutterFlow() { return; } + // Null the pending data before any await: it is only cleared at the end of + // this function otherwise, so a second confirm click landing mid-commit + // would read the same data and push twice concurrently. const commitData = pendingCommitData; + pendingCommitData = null; commitTargetProjectId = readCommitTargetProjectId(); closeCommitConfirmModal(); showCommitProgress({ withProvisioning: commitNeedsProvisioning(commitData) }); @@ -5466,11 +5572,12 @@ async function confirmCommitToFlutterFlow() { const { codeInfo } = commitData; - const { artifactType, artifactName } = getCurrentArtifactMetadata(); + const { artifactType, artifactName, fileName } = getCurrentArtifactMetadata(); const result = await executeCommit(codeInfo.content, { artifactType, artifactName, + fileName, pipelineResult: { step1Result: pipelineState.step1Result, selectedModel: document.getElementById("code-generator-model")?.value, @@ -5485,8 +5592,6 @@ async function confirmCommitToFlutterFlow() { } else { showCommitFailureModal(result); } - - pendingCommitData = null; } // Global exports diff --git a/dist/assets/index-I7INJLip.js b/dist/assets/index-D53cwu4I.js similarity index 66% rename from dist/assets/index-I7INJLip.js rename to dist/assets/index-D53cwu4I.js index 067cf41..a31efa4 100644 --- a/dist/assets/index-I7INJLip.js +++ b/dist/assets/index-D53cwu4I.js @@ -1,8 +1,8 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(i){if(i.ep)return;i.ep=!0;const n=s(i);fetch(i.href,n)}})();var m=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:m,ke=we==null?void 0:we.navigator,F=we==null?void 0:we.document,re=we==null?void 0:we.location,Fo=we==null?void 0:we.fetch,In=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Ca=we==null?void 0:we.AbortController,Jd=we==null?void 0:we.CompressionStream,Pe=ke==null?void 0:ke.userAgent;function fc(){return!(!m||m.navigator.onLine===!1)}var Is=typeof globalThis<"u"?globalThis:m;Is&&typeof self>"u"&&(Is.self=Is),Is&&typeof File>"u"&&(Is.File=function(){});var T=m??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Fa(t,e,s,r,i,n,o){try{var a=t[n](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,i)}function X(t){return function(){var e=this,s=arguments;return new Promise(function(r,i){var n=t.apply(e,s);function o(l){Fa(n,r,i,o,a,"next",l)}function a(l){Fa(n,r,i,o,a,"throw",l)}o(void 0)})}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},b.apply(null,arguments)}function gc(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var Pa=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Aa(t){return typeof t=="string"||t}function Ra(t){return typeof t=="string"?t:void 0}var Cs,Yd=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],ct=function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t}({}),Ta=function(t){return t.GZipJS="gzip-js",t.Base64="base64",t}({}),Zd=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],Xd=["token"],mc="NativeGzipValidationError",Cn=t=>t.length>=2&&t[0]===31&&t[1]===139,$a=(t,e)=>t===Ta.GZipJS||e===Ta.GZipJS||e==="gzip",Ma=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",gr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=mc,e},Qd=function(){var t=X(function*(e,s){18>e.size&&gr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Cn(r)&&r[2]===8||gr("invalid-header");var i=new DataView(yield e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Cs)return Cs;Cs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Cs[c]=d>>>0}return Cs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&gr("invalid-crc");var n=s.length>>>0;i.getUint32(4,!0)!==n&&gr("invalid-size")});return function(e,s){return t.apply(this,arguments)}}();function Fn(){return Fn=X(function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),o=n.write(r).then(()=>n.close()).catch(function(){var u=X(function*(c){try{yield n.abort(c)}catch{}throw c});return function(c){return u.apply(this,arguments)}}()),a=new Response(i.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield Qd(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}}),Fn.apply(this,arguments)}var eh=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],Na=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return eh.concat(e).some(r=>{var i=r.toLowerCase();return s.indexOf(i)!==-1})};function O(t,e){return t.indexOf(e)!==-1}var ki=function(t){return t.trim()},Pn=function(t){return t.replace(/^\$/,"")};function vc(t){var e,s=[];return(e=JSON.stringify(t,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(i))return"[Circular]";s.push(i)}return i}}))!==null&&e!==void 0?e:"null"}var _c=Object.prototype,yc=_c.hasOwnProperty,Ii=_c.toString,L=Array.isArray||function(t){return Ii.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!L(t),gt=t=>{if(te(t)){for(var e in t)if(yc.call(t,e))return!1;return!0}return!1},I=t=>t===void 0,W=t=>Ii.call(t)=="[object String]",An=t=>W(t)&&t.trim().length===0,Re=t=>t===null,D=t=>I(t)||Re(t),he=t=>Ii.call(t)=="[object Number]"&&t==t,at=t=>he(t)&&t>0,Ge=t=>Ii.call(t)==="[object Boolean]",th=t=>t instanceof FormData,sh=t=>O(Zd,t),rh=t=>O(Xd,t);function wc(t){return t===null||typeof t!="object"}function Hr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Po(t){return typeof Event<"u"&&bc(t,Event)}function bc(t,e){try{return t instanceof e}catch{return!1}}var ih=[!0,"true",1,"1","yes"],Vi=t=>O(ih,t),nh=[!1,"false",0,"0","no"];function st(t,e,s,r,i){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+i),st(i||s,e,s,r))}class oh{constructor(e){this.tt={},this.et=e.et,this.it=st(e.bucketSize,0,100,e.rt),this.nt=st(e.refillRate,0,this.it,e.rt),this.st=st(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),i=String(e),n=this.tt[i];return n?this.ot(n,r):this.tt[i]=n={tokens:this.it,lastAccess:r},n.tokens===0||(n.tokens--,n.tokens===0&&((s=this.et)==null||s.call(this,e)),n.tokens===0)}stop(){this.tt={}}}var Le="Mobile",Wr="iOS",mt="Android",ps="Tablet",Ec=mt+" "+ps,Sc="iPad",xc="Apple",kc=xc+" Watch",Ws="Safari",fs="BlackBerry",Ic="Samsung",Cc=Ic+"Browser",Fc=Ic+" Internet",qt="Chrome",ah=qt+" OS",Pc=qt+" "+Wr,Ao="Internet Explorer",Ac=Ao+" "+Le,Ro="Opera",lh=Ro+" Mini",To="Edge",Rc="Microsoft "+To,cs="Firefox",Tc=cs+" "+Wr,Zs="Nintendo",Xs="PlayStation",us="Xbox",$c=mt+" "+Le,Mc=Le+" "+Ws,Os="Windows",Rn=Os+" Phone",Oa="Nokia",Tn="Ouya",Nc="Generic",ch=Nc+" "+Le.toLowerCase(),Oc=Nc+" "+ps.toLowerCase(),$n="Konqueror",Lc="Oculus Browser",zr="Vivaldi",Bc="Yandex",qr="Whale",Mn="DuckDuckGo",Dc="Pale Moon",Vr="Waterfox",zs="Brave",jc="Google Search App",le="(\\d+(\\.\\d+)?)",Gi=new RegExp("Version/"+le),uh=new RegExp(us,"i"),dh=new RegExp(Xs+" \\w+","i"),hh=new RegExp(Zs+" \\w+","i"),$o=new RegExp(fs+"|PlayBook|BB10","i"),ph={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},Uc=function(t,e,s,r){e=e||"";var i=function(n){return n!=null&&n.brave?zs:null}(s);return i||(r!=null&&r.detectGoogleSearchApp&&O(t,"GSA/")?jc:O(t," OPR/")&&O(t,"Mini")?lh:O(t," OPR/")?Ro:$o.test(t)?fs:O(t,"IE"+Le)||O(t,"WPDesktop")?Ac:O(t,"OculusBrowser")?Lc:O(t,Cc)?Fc:O(t,To)||O(t,"Edg/")?Rc:O(t,zr+"/")?zr:O(t,"YaBrowser/")?Bc:O(t,qr+"/")?qr:O(t,Mn+"/")||O(t,"Ddg/")?Mn:O(t,"FBIOS")?"Facebook "+Le:O(t,"UCWEB")||O(t,"UCBrowser")?"UC Browser":O(t,"CriOS")?Pc:O(t,"CrMo")||O(t,qt)?qt:O(t,mt)&&O(t,Ws)?$c:O(t,"FxiOS")?Tc:O(t.toLowerCase(),$n.toLowerCase())?$n:O(t,zs+"/")?zs:((n,o)=>o&&O(o,xc)||function(a){return O(a,Ws)&&!O(a,qt)&&!O(a,mt)}(n))(t,e)?O(t,Le)?Mc:Ws:O(t,"PaleMoon/")?Dc:O(t,Vr+"/")?Vr:O(t,cs)?cs:O(t,"MSIE")||O(t,"Trident/")?Ao:O(t,"Gecko")?cs:"")},fh={[Ac]:[new RegExp("rv:"+le)],[Rc]:[new RegExp(To+"?\\/"+le)],[qt]:[new RegExp("("+qt+"|CrMo)\\/"+le)],[Pc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Ws]:[Gi],[Mc]:[Gi],[Ro]:[new RegExp("(Opera|OPR)\\/"+le)],[cs]:[new RegExp(cs+"\\/"+le)],[Tc]:[new RegExp("FxiOS\\/"+le)],[$n]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),Gi],[$c]:[new RegExp("android\\s"+le,"i")],[Fc]:[new RegExp(Cc+"\\/"+le)],[Lc]:[new RegExp("OculusBrowser\\/"+le)],[zr]:[new RegExp(zr+"\\/"+le)],[Bc]:[new RegExp("YaBrowser\\/"+le)],[qr]:[new RegExp(qr+"\\/"+le)],[zs]:[new RegExp(zs+"\\/"+le)],[Mn]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Dc]:[new RegExp("PaleMoon\\/"+le)],[Vr]:[new RegExp(Vr+"\\/"+le)],[jc]:[new RegExp("GSA\\/"+le)],[Ao]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},gh=function(t,e,s,r){var i=Uc(t,e,s,r),n=fh[i];if(I(n))return null;for(var o=0;n.length>o;o++){var a=t.match(n[o]);if(a)return parseFloat(a[a.length-2])}return null},La=[[new RegExp(us+"; "+us+" (.*?)[);]","i"),t=>[us,t&&t[1]||""]],[new RegExp(Zs,"i"),[Zs,""]],[new RegExp(Xs,"i"),[Xs,""]],[$o,[fs,""]],[new RegExp(Os,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Rn,""];if(new RegExp(Le).test(e)&&!/IEMobile\b/.test(e))return[Os+" "+Le,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=ph[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Os,r]}return[Os,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[Wr,[t[3],t[4],t[5]||"0"].join(".")]:[Wr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=I(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+mt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+mt+")","i"),t=>t&&t[2]?[mt,[t[2],t[3],t[4]||"0"].join(".")]:[mt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ah,""]],[/Linux|debian/i,["Linux",""]]],Ba=function(t){return hh.test(t)?Zs:dh.test(t)?Xs:uh.test(t)?us:new RegExp(Tn,"i").test(t)?Tn:new RegExp("("+Rn+"|WPDesktop)","i").test(t)?Rn:/iPad/.test(t)?Sc:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?kc:$o.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Oa,"i").test(t)?Oa:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Le).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?mt:Ec:new RegExp("(pda|"+Le+")","i").test(t)?ch:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Oc:""},mh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Da(t,e){return typeof(s=t)=="string"&&mh.test(s)?t:e();var s}function It(t){return t&&t.split("#")[0]}function Mo(t,e){var s=setTimeout(t,e);return s!=null&&s.unref&&(s==null||s.unref()),s}function ja(t,e,s){return Hc.apply(this,arguments)}function Hc(){return(Hc=X(function*(t,e,s){var r;try{return yield Promise.race([t,new Promise((i,n)=>{r=Mo(()=>{try{s==null||s(),i()}catch(o){n(o)}},e)})])}finally{clearTimeout(r)}})).apply(this,arguments)}var vh=t=>t instanceof Error,Wc={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},_h=Wc.info;function zc(t){if(Ge(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(L(t))return{arrayValue:{values:t.map(e=>zc(e))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Gr(t){var e=[];for(var s in t){var r=t[s];Re(r)||I(r)||e.push({key:s,value:zc(r)})}return e}function yh(t,e){var s=Wc[t.level||"info"]||_h,r=s.text,i=s.number,n=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:n,observedTimeUnixNano:n,severityNumber:i,severityText:r,body:{stringValue:t.body},attributes:Gr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),I(t.trace_flags)||(l.flags=t.trace_flags),l}function qc(t,e,s){return b({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function Vc(t,e,s,r){return{resourceLogs:[{resource:{attributes:Gr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let wh=class{constructor(t,e,s,r,i,n,o){var a;n===void 0&&(n=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=i,this.dt=n,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var s={record:yh(e,this.ut())};this.ht(()=>this.At(s))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var i of s)try{var n=i(r);if(!n)return this.rt.info("Log was rejected in beforeSend function"),null;r=n}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X(function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally(()=>{t.ct=null})),t.ct})()}Ft(){var t=this;return X(function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ct.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,i=0;s.length>0&&r>i;){var n,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=Vc(l.map(d=>d.record),t.Lt(),(n=t.vt)!==null&&n!==void 0?n:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),s=(o=t._instance.getPersistedProperty(ct.LogsQueue))!==null&&o!==void 0?o:[],i+=l.length,c.kind==="fatal"))throw c.error}})()}Dt(t){var e=this;return X(function*(){var s,r=Math.max(0,t-e.ft),i=(s=e._instance.getPersistedProperty(ct.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ct.LogsQueue,i.slice(r)),yield e.dt()})()}Lt(){return qc(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ct.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ct.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Mo(()=>{this.Nt=void 0,this.It()},t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(ct.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return X(function*(){e.Et();var s=e.flush().catch(()=>{});t!==void 0?yield ja(s,t):yield s})()}flushWithTimeout(t){var e=this;return X(function*(){var s=e.flush();yield ja(s,t,()=>{s.catch(()=>{})})})()}It(){this.flush().then(()=>{this.yt=0},t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)}).finally(()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())})}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var Ki=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Ua(t){return String(t)+"000000"}function Ha(t,e,s,r){var i="";return r&&(i=Object.keys(r).sort().map(n=>JSON.stringify(n)+":"+JSON.stringify(r[n])).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+i}let bh=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s==null?void 0:s.unit,attributes:s==null?void 0:s.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s==null?void 0:s.unit,attributes:s==null?void 0:s.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s==null?void 0:s.unit,attributes:s==null?void 0:s.attributes})}flush(){var t=this,e=this.ct,s=function(){var i=X(function*(){e&&(yield e.catch(()=>{})),yield t.Zt()});return function(){return i.apply(this,arguments)}}(),r=s().finally(()=>{this.ct===r&&(this.ct=null)});return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?b({},e.attributes):void 0,r=Ha(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var i=this.Bt.get(r);if(!i){if(!this.Qt())return;i={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,i)}var n=this.Ut.get(e.name);n===void 0?this.Ut.set(e.name,e.type):n===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+n+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(i,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(Ki.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[function(i,n){for(var o=0;n.length>o;o++)if(n[o]>=i)return o;return n.length}(e,Ki)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=L(e)?e:[e],r=t;for(var i of s)try{var n=i(r);if(!n)return this.rt.info("Metric was rejected in beforeSend function"),null;r=n}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Mo(()=>{this.Nt=void 0,this.flush().catch(t=>{this.rt.error("Metrics flush failed:",t)})},this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X(function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}})()}Gt(t){return e=this.Xt(t),s=function(n,o,a){return b({},n.resourceAttributes,{"service.name":n.serviceName||"unknown_service"},n.environment&&{"deployment.environment":n.environment},n.serviceVersion&&{"service.version":n.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})}(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Gr(s)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]};var e,s,r,i}Xt(t){var e=Ua(Date.now()),s=new Map;for(var r of t.values()){var i,n=Ha(r.type,r.name,r.unit,void 0),o=s.get(n);o||(o=b({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(n,o));var a=Gr((i=r.attributes)!==null&&i!==void 0?i:{}),l=Ua(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Ki})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var i=r[0],n=r[1],o=this.Bt.get(i);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=n.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=n.hist.bucketCounts[a]}else o.hist=n.hist}else this.Qt()&&this.Bt.set(i,n)}}};var mr,Wa,Ji;function Eh(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return Ji&&s.length===Wa||(Wa=s.length,Ji=s.reduce((r,i)=>{mr||(mr={});var n=mr[i];if(n)r[n[0]]=n[1];else for(var o=t(i),a=o.length-1;a>=0;a--){var l=o[a],u=l==null?void 0:l.filename,c=e[i];if(u&&c){r[u]=c,mr[i]=[u,c];break}}return r},{})),Ji}}class Sh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,s,0).apply(e),n=this.buildParsingContext(s),o=this.parseStacktrace(i,n);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X(function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&L(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,i;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),b({},e,{cause:r,stack:i})}applyChunkIds(e,s){return e.map(r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X(function*(){var r=e;for(var i of s.modifiers)r=yield i(r);return r})()}convertToExceptionList(e,s){var r,i,n,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(i=s.handled)===null||i===void 0||i,synthetic:(n=e.synthetic)!==null&&n!==void 0&&n}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Eh(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var i=(n,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(n,a)}};return b({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:n=>i(n,r),next:n=>i(n,r+1)})}}var gs="?";function Nn(t,e,s,r,i){var n={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return I(r)||(n.lineno=r),I(i)||(n.colno=i),n}var Gc=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},xh=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,kh=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Ih=/\((\S*)(?::(\d+))(?::(\d+))\)/,Ch=(t,e)=>{var s=xh.exec(t);if(s)return Nn(e,s[1],gs,+s[2],+s[3]);var r=kh.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var i=Ih.exec(r[2]);i&&(r[2]=i[1],r[3]=i[2],r[4]=i[3])}var n=Gc(r[1]||gs,r[2]);return Nn(e,n[1],n[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Fh=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Ph=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Ah=(t,e)=>{var s=Fh.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Ph.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var i=s[3],n=s[1]||gs,o=Gc(n,i);return Nn(e,i=o[1],n=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},za=/\(error: (.*)\)/;class Rh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Hr(e,"DOMException")}isDOMError(e){return Hr(e,"DOMError")}}class Th{match(e){return function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return bc(s,Error)}}(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class $h{constructor(){}match(e){return!!Hr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var i=s.apply(e.message);return b({},i,{stack:(r=this.pe(e))!==null&&r!==void 0?r:i.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,i,n=(r=s.lineno)!==null&&r!==void 0?r:0,o=(i=s.colno)!==null&&i!==void 0?i:0;return`Error - at `+s.filename+":"+n+":"+o}}}var Mh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class Nh{match(e){return typeof e=="string"}coerce(e,s){var r,i=this.getInfos(e),n=i[0],o=i[1];return{type:n??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,i=e.match(Mh);return i&&(s=i[1],r=i[2]),[s,r]}}var Oh=["fatal","error","warning","log","info","debug"];function Kc(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var i=s.slice(0,r).join(", ");if(e>=i.length)return r===s.length?i:i.length>e?i.slice(0,e)+"...":i}return""}class Lh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,i,n=this.getErrorPropertyFromObject(e);return n?s.apply(n):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(i=s.syntheticException)==null?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Po(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+Kc(e)}isSeverityLevel(e){return W(e)&&!An(e)&&Oh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(vh(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Bh{match(e){return Po(e)}coerce(e,s){var r,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+Kc(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class Dh{match(e){return wc(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class jh{match(e){return Hr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Po(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,i=this.getUnhandledRejectionReason(e);return wc(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Kr="$message",Jr="$timestamp",Uh=new Set([Kr,Jr]),Yi={enabled:!0,max_bytes:32768};function Yr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Yi.enabled,max_bytes:Wh(t.max_bytes,Yi.max_bytes)}:b({},Yi)}class Hh{constructor(e){this.Ke=[],this.Je=0,this.Ne=Yr(e)}setConfig(e){this.Ne=Yr(e),this.Xe()}add(e){var s=function(i){var n;try{n=vc(i)}catch{return}try{var o=JSON.parse(n);if(!te(o))return;var a=o,l=a[Kr],u=a[Jr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:n}}catch{return}}(e);if(s){var r=function(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i).length;for(var n=encodeURIComponent(i),o=0,a=0;n.length>a;a++)n[a]==="%"?(o+=1,a+=2):o+=1;return o}(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map(e=>e.step)}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Wh(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var Jc=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(i){if(m&&(Y.DEBUG||m.POSTHOG_DEBUG||s)&&!I(m.console)&&m.console){for(var n=("__rrweb_original__"in m.console[i])?m.console[i].__rrweb_original__:m.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];n(t,...a)}},debug(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("debug",...n)},info(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("log",...n)},warn(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("warn",...n)},error(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("error",...n)},critical(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];console.error(t,...n)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,n)=>Jc(t+" "+i,n)};return r},C=Jc("[PostHog.js]"),se=C.createLogger,zh=se("[ExternalScriptsLoader]"),Zi=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return zh.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=F==null?void 0:F.querySelectorAll("script");if(r){for(var i,n=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)}),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(i=n())return i.v}var a=()=>{if(!F)return s("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F==null||F.addEventListener("DOMContentLoaded",a)};T.__PosthogExtensions__=T.__PosthogExtensions__||{},T.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var i="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var n=3e5;i=i+"&t="+Math.floor(Date.now()/n)*n}r=t.requestRouter.endpointFor("assets",i)}Zi(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");Zi(t,o,s)}},T.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);Zi(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var Yc="$people_distinct_id",Qs="$device_id",Xi="$device_model",Ls="__alias",Bs="__timers",On="$autocapture_disabled_server_side",Ln="$heatmaps_enabled_server_side",Bn="$exception_capture_enabled_server_side",Dn="$error_tracking_suppression_rules",jn="$error_tracking_capture_extension_exceptions",Un="$web_vitals_enabled_server_side",No="$dead_clicks_enabled_server_side",Oo="$product_tours_enabled_server_side",Hn="$web_vitals_allowed_metrics",zt="$session_recording_remote_config",Zc="$replay_sample_rate",Xc="$replay_override_sampling",Qc="$replay_override_linked_flag",eu="$replay_override_url_trigger",tu="$replay_override_event_trigger",as="$sesid",Lo="$session_is_sampled",Lt="$enabled_feature_flags",Ds="$active_feature_flags",Fr="$early_access_features",Wn="$feature_flag_details",js="$feature_flag_payloads",Pr="$feature_flag_request_id",Zr="$minimal_flag_called_events",Qe="$override_feature_flags",Bt="$override_feature_flag_payloads",lt="$stored_person_properties",Dt="$stored_group_properties",zn="$surveys",Xr="$surveys_loaded_at",qn="$surveys_activated",Ar="$surveys_activated_session",Rr="$surveys_activated_timestamps",Us="ph_product_tours",Ut="$flag_call_reported",Hs="$flag_call_reported_session_id",Tr="$feature_flag_errors",qs="$feature_flag_evaluated_at",He="$user_state",Vn="$client_session_props",Gn="$capture_rate_limit",Kn="$initial_campaign_params",Jn="$initial_referrer_info",Qr="$initial_person_info",ei="$epp",vr="$posthog_cookieless",su="$cookieless_mode",ru="$sdk_debug_extensions_init_method",iu="$sdk_debug_extensions_init_time_ms",nu="$sdk_debug_recording_script_not_loaded",Bo="PostHog loadExternalDependency extension not found.",jt="on_reject",dt="always",Qt="anonymous",Rt="identified",Yn="identified_only",ti="visibilitychange",si="beforeunload",is="$pageview",Qi="$pageleave",en="$identify",qa="$groupidentify";function _r(t,e){L(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(L(t))t.forEach(e);else if(th(t))t.forEach((r,i)=>e(r,i));else for(var s in t)yc.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var i of s)for(var n in i)i[n]!==void 0&&(t[n]=i[n]);return t};function $r(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var Va=function(t){try{return t()}catch{return}},qh=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(i){C.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),C.critical(i)}}},Do=function(t){var e={};return Z(t,function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)}),e},Vh=["herokuapp.com","vercel.app","netlify.app"];function Gh(t){var e=t==null?void 0:t.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of Vh)if(s===r)return!1;return!0}function ie(t,e,s,r){var i=r??{},n=i.capture,o=i.passive;t==null||t.addEventListener(e,s,{capture:n!==void 0&&n,passive:o===void 0||o})}function Zn(t){return t.name==="ph_toolbar_internal"}var ou=t=>{if(F){try{for(var e=t+"=",s=F.cookie.split(";").filter(n=>n.length),r=0;s.length>r;r++){for(var i=s[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class ri{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,i){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(i)||0>e||0>s||0>r||0>i||e>0xffffffffffff||s>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var n=new Uint8Array(16);return n[0]=e/Math.pow(2,40),n[1]=e/Math.pow(2,32),n[2]=e/Math.pow(2,24),n[3]=e/Math.pow(2,16),n[4]=e/256,n[5]=e,n[6]=112|s>>>8,n[7]=s,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new ri(n)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ri(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class Kh{generate(){var e=this.generateOrAbort();if(!I(e))return e;this.S=0;var s=this.generateOrAbort();if(I(s))throw new Error("Could not generate UUID after timestamp reset");return s}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return ri.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new Jh}}var Ga,au=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};m&&!I(m.crypto)&&crypto.getRandomValues&&(au=t=>crypto.getRandomValues(t));class Jh{nextUint32(){return this.R.length>this.O||(au(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var ut=()=>Yh().toString(),Yh=()=>(Ga||(Ga=new Kh)).generate(),Fs="",Zh=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,ht={N:()=>!!F,j(t){C.error("cookieStore error: "+t)},P:ou,H(t){var e;try{e=JSON.parse(ht.P(t))||{}}catch{}return e},F(t,e,s,r,i){if(!F)return!1;try{var n="",o="",a=function(c,d){if(d){var h=function(f,g){if(g===void 0&&(g=F),Fs)return Fs;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var v=f.split("."),_=Math.min(v.length,8),w="dmn_chk_"+ut();!Fs&&_--;){var S=v.slice(_).join("."),k=w+"=1;domain=."+S+";path=/";g.cookie=k+";max-age=3",g.cookie.includes(w)&&(g.cookie=k+";max-age=0",Fs=S)}return Fs}(c);if(!h){var p=(f=>{var g=f.match(Zh);return g?g[0]:""})(c);p!==h&&C.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""}(F.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),n="; expires="+l.toUTCString()}i&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+n+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&C.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{ht.F(t,"",-1,e)}catch{return}}},tn=null,Q={N(){if(!Re(tn))return tn;var t=!0;if(I(m))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||C.error("localStorage unsupported; falling back to cookie store"),tn=t,t},j(t){C.error("localStorage error: "+t)},P(t){try{return m==null?void 0:m.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return m==null||m.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{m==null||m.localStorage.removeItem(t)}catch(e){Q.j(e)}}},Xh=[Qs,"distinct_id",as,Lo,ei,Qr,He],yr={},Qh={N:()=>!0,j(t){C.error("memoryStorage error: "+t)},P:t=>yr[t]||null,H:t=>yr[t]||null,F:(t,e)=>(yr[t]=e,!0),q(t){delete yr[t]}},Tt=null,ce={N(){if(!Re(Tt))return Tt;if(Tt=!0,I(m))Tt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Tt=!1),ce.q(t)}catch{Tt=!1}return Tt},j(t){C.error("sessionStorage error: ",t)},P(t){try{return m==null?void 0:m.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return m==null||m.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{m==null||m.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class ep{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===dt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===jt}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Vi(e)?1:O(nh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:ht;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?ht:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Vi(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke==null?void 0:ke.doNotTrack,ke==null?void 0:ke.msDoNotTrack,T.doNotTrack].some(e=>Vi(e))}}function lu(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var i=r(e);return W(i)&&i?i:e}catch(n){return C.error("Error in get_current_url, falling back to window.location.href",n),e}}var cu="__POSTHOG_TOOLBAR__",tp=1,sp=3,rp=11;function Ka(t){return t instanceof Element&&(t.id===cu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ct(t){return!!t&&t.nodeType===tp}function Ne(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function uu(t){return!!t&&t.nodeType===sp}function du(t){return!!t&&t.nodeType===rp&&Ct(t.host)}var hu=1e3;function jo(t){return t?ki(t).split(/\s+/):[]}function Ja(t,e){var s=function(r){var i,n=m==null||(i=m.location)==null?void 0:i.href;return I(n)?void 0:lu(r,n)}(e);return!!(s&&t&&t.some(r=>s.match(r)))}function ii(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return jo(e)}function pu(t){return D(t)?null:ki(t).split(/(\s+)/).filter(e=>Vs(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function er(t){var e="";return Qn(t)&&!vu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,function(s){var r;uu(s)&&s.textContent&&(e+=(r=pu(s.textContent))!==null&&r!==void 0?r:"")}),ki(e)}function sn(t){var e;return I(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Uo=["a","button","form","input","select","textarea","label"];function Xn(t,e){if(I(e))return!0;var s,r=function(n){if(e.some(o=>function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}}(n,o)))return{v:!0}};for(var i of t)if(s=r(i))return s.v;return!1}function fu(t){var e=t.parentNode;return!(!e||!Ct(e))&&e}var ip=[".ph-no-autocapture","[data-ph-no-autocapture]"],gu=["next","previous","prev",">","<"],np=[...gu,"+","-","−","–"],Ya=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Za=[".ph-no-rageclick",".ph-no-capture"],op=["","text","search","email","password","url","tel","number"];function Xa(t,e){if(!m||Ho(t))return!1;var s,r,i,n,o;if(Ge(e)?(s=!!e&&Za,r=void 0,i=!1):(s=(n=e==null?void 0:e.css_selector_ignorelist)!==null&&n!==void 0?n:Za,r=e==null?void 0:e.content_ignorelist,i=(o=e==null?void 0:e.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||i&&function(l){return!(!l||!Ct(l))&&(!!Ne(l,"textarea")||(Ne(l,"input")?O(op,(l.getAttribute("type")||"").toLowerCase()):function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""}(l)))}(t))return!1;var a=mu(t,!1).targetElementList;return!function(l,u){if(l===!1||I(l))return!1;var c;if(l===!0)c=gu;else{if(!L(l))return!1;if(l.length>10)return C.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map(d=>d.toLowerCase())}return u.some(d=>{var h=d.safeText,p=d.ariaLabel;return c.some(f=>Ya(h,f)||Ya(p,f))})}(r,a.map(l=>{var u;return{safeText:er(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}}))&&!Xn(a,s)}var Ho=t=>!t||Ne(t,"html")||!Ct(t),mu=(t,e)=>{if(!m||Ho(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],i=t;i.parentNode&&!Ne(i,"body");)if(du(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var n=fu(i);if(!n)break;if(e||Uo.indexOf(n.tagName.toLowerCase())>-1)s=!0;else try{var o=m.getComputedStyle(n);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(n),i=n}return{parentIsUsefulElement:s,targetElementList:r}};function Qn(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Ne(r,"body");r=r.parentNode){if(s++>=hu||e.has(r))return!1;e.add(r);var i=ii(r);if(O(i,"ph-sensitive")||O(i,"ph-no-capture"))return!1}if(O(ii(t),"ph-include"))return!0;var n=t.type||"";if(W(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function vu(t){return!!(Ne(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Ne(t,"select")||Ne(t,"textarea")||t.getAttribute("contenteditable")==="true")}var Qa=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),el=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,ap=[16,15,14,13],lp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),tl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),sl=/[0-9A-Za-z_]/;function cp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var i=t.charCodeAt(r)-48;s&&(i*=2)>9&&(i-=9),e+=i,s=!s}return e%10==0}function Vs(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=ki(t);var s=e?Qa.test((t||"").replace(/[- ]/g,"")):function(i){var n;for(el.lastIndex=0;n=el.exec(i);){var o=n[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of ap){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(Qa.test(d)&&cp(d))return!0}}}return!1}(t);if(s)return!1;var r=e?lp.test(t):function(i){var n;for(tl.lastIndex=0;n=tl.exec(i);){var o=n[1],a=n[3];if(!(o&&a&&sl.test(o)&&sl.test(a)))return!0}return!1}(t);if(r)return!1}return!0}function rl(t){var e=er(t);return Vs(e=(e+" "+_u(t)).trim())?e:""}function _u(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=er(s);e=(e+" "+i).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+_u(s)).trim())}catch(n){C.error("[AutoCapture]",n)}}),e}function il(t){return t.replace(/"|\\"/g,'\\"')}function up(t){var e=t.attr__class;if(e)return L(e)?e:jo(e)}var wr=se("[Dead Clicks]"),dp=()=>!0,hp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(No)),r=t.instance.config.capture_dead_clicks;return Ge(r)?r:!!te(r)||s};class nl{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[No]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai(()=>{this.oi()}):this.stop()}ai(e){var s,r;(s=T.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=T.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",i=>{i?wr.error("failed to load script",i):e()})}oi(){var e;if(F){if(!this.si&&(e=T.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=T.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(F),wr.info("starting...")}}else wr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,wr.info("stopping..."))}}var rn=se("[SegmentIntegration]"),yu="posthog-js";function wu(t,e){var s=e===void 0?{}:e,r=s.organization,i=s.projectId,n=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var v=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=v,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],S=w.map(E=>b({},E,{stacktrace:E.stacktrace?b({},E.stacktrace,{type:"raw",frames:(E.stacktrace.frames||[]).map(P=>b({},P,{platform:"web:javascript"}))}):void 0})),k={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&i&&(k.$sentry_url=(n||"https://sentry.io/organizations/")+r+"/issues/?project="+i+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(k)),c}}class pp{constructor(e,s,r,i,n,o){this.name=yu,this.setupOnce=function(a){a(wu(e,{organization:s,projectId:r,prefix:i,severityAllowList:n,sendExceptionsToPostHog:o==null||o}))}}}class ol{constructor(e){this.li=(s,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(C.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:i}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,s){var r,i=this.vi(e,s);return this.ui={pathname:(r=m==null?void 0:m.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var i={$pageview_id:s,$prev_pageview_id:r.pageViewId},n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){var o=n.maxScrollHeight,a=n.lastScrollY,l=n.maxScrollY,u=n.maxContentHeight,c=n.lastContentY,d=n.maxContentY;if(!(I(o)||I(a)||I(l)||I(u)||I(c)||I(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?st(a/o,0,1,C):1,p=o>1?st(l/o,0,1,C):1,f=u>1?st(c/u,0,1,C):1,g=u>1?st(d/u,0,1,C):1;i=ee(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),i}}var nn=["flags","surveys"],fp={[Yc]:{exposure:"hidden"},[Ls]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Bs]:{exposure:"hidden"},[On]:{exposure:"event"},[Ln]:{exposure:"hidden"},[Bn]:{exposure:"event"},[Dn]:{exposure:"hidden"},[jn]:{exposure:"event"},[Un]:{exposure:"event"},[No]:{exposure:"event"},[Oo]:{exposure:"hidden"},[Hn]:{exposure:"event"},[zt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[as]:{exposure:"hidden"},[Lo]:{exposure:"event"},[Zc]:{exposure:"event",shouldSkipFromEventProperties:t=>Re(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Lt]:{exposure:"hidden",storageGroup:"flags"},[Ds]:{exposure:"hidden",storageGroup:"flags"},[Fr]:{exposure:"hidden"},[Wn]:{exposure:"hidden",storageGroup:"flags"},[js]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Zr]:{exposure:"hidden",storageGroup:"flags"},[Qe]:{exposure:"hidden"},[Bt]:{exposure:"hidden"},[lt]:{exposure:"hidden"},[Dt]:{exposure:"hidden"},[zn]:{exposure:"hidden",storageGroup:"surveys"},[Xr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[qn]:{exposure:"event"},[Ar]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Us]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Ut]:{exposure:"hidden"},[Hs]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[qs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Vn]:{exposure:"hidden"},[Gn]:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},[Qr]:{exposure:"hidden"},[ei]:{exposure:"hidden"},[Xc]:{exposure:"event"},[Qc]:{exposure:"event"},[eu]:{exposure:"event"},[tu]:{exposure:"event"},[ru]:{exposure:"event"},[iu]:{exposure:"event"},[nu]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},gp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],$t=t=>{var e=fp[t];if(e)return e;for(var s of gp){var r=s[1];if(t.indexOf(s[0])===0)return r}},ls=(t,e)=>{try{return JSON.stringify(t,(s,r)=>typeof r=="bigint"?r.toString():r,e)}catch{return vc(t)}},ni=t=>{var e=F==null?void 0:F.createElement("a");return I(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var n=r[i].split("=");if(n[0]===e){s=n;break}}if(!L(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{C.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},tr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),i=r[1],n=(r[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");L(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),i!=null&&(h+="#"+i),h},oi=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},bu=(t,e)=>t>=e&&fc(),Eu=(t,e,s,r)=>{if(t===0){if(fc()){var i=e+1;return i===s&&r(),i}return e}return 0},br="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],mp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],sr="",vp=["li_fat_id"];function Su(t,e,s){if(!F)return{};var r,i=e?[...vs,...s||[]]:[],n=xu(tr(F.URL,i,sr),t),o=(r={},Z(vp,function(a){var l=ou(a);r[a]=l||null}),r);return ee(o,n)}function xu(t,e){var s=mp.concat(e||[]),r={};return Z(s,function(i){var n=ms(t,i);r[i]=n||null}),r}function ku(t){var e=function(n){return n?n.search(br+"google.([^/?]*)")===0?"google":n.search(br+"bing.com")===0?"bing":n.search(br+"yahoo.com")===0?"yahoo":n.search(br+"duckduckgo.com")===0?"duckduckgo":null:null}(t),s=e!="yahoo"?"q":"p",r={};if(!Re(e)){r.$search_engine=e;var i=F?ms(F.referrer,s):"";i.length&&(r.ph_keyword=i)}return r}function al(){return navigator.language||navigator.userLanguage}var ai="$direct";function Iu(){return(F==null?void 0:F.referrer)||ai}function Cu(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],i=s?It(re==null?void 0:re.href):re==null?void 0:re.href,n=i==null?void 0:i.substring(0,1e3);return{r:Iu().substring(0,1e3),u:n?tr(n,r,sr):void 0}}function Fu(t,e){var s;e===void 0&&(e=!1);var r=t.r,i=t.u,n=e?It(i):i,o={$referrer:r,$referring_domain:r==null?void 0:r==ai?ai:(s=ni(r))==null?void 0:s.host};if(n){o.$current_url=n;var a=ni(n);o.$host=a==null?void 0:a.host,o.$pathname=a==null?void 0:a.pathname;var l=xu(n);ee(o,l)}if(r){var u=ku(r);ee(o,u)}return o}function Pu(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function _p(){try{return new Date().getTimezoneOffset()}catch{return}}var yp={flags:qs,surveys:Xr},wp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],es="main";class on{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(n=>{var o="";return n.token&&(o=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&C.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,s),this.save(),m){var i=()=>this.flush();ie(m,"beforeunload",i,{capture:!1}),ie(m,"pagehide",i,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){wp.indexOf(e.persistence.toLowerCase())===-1&&(C.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...Xh,...o];return b({},Q,{H(u){try{var c={};try{c=ht.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];Re(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var v={};l.forEach(_=>{c[_]&&(v[_]=c[_])}),Object.keys(v).length&&ht.F(u,v,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{m==null||m.localStorage.removeItem(u),ht.q(u,c)}catch(d){Q.j(d)}}})}(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),i=!1,n=e.persistence.toLowerCase();return n==="localstorage"&&Q.N()?(s=Q,i=!0):n==="localstorage+cookie"&&r.N()?(s=r,i=!0):n==="sessionstorage"&&ce.N()?s=ce:n==="memory"?s=Qh:n==="cookie"?s=ht:r.N()?(s=r,i=!0):s=ht,this.fi=i,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,(s,r)=>{var i=$t(r);if(!i||i.exposure==="event"){if(i!=null&&i.shouldSkipFromEventProperties!=null&&i.shouldSkipFromEventProperties(s))return;e[r]=s}}),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of nn){var s=Q.H(this.Si(e));if(s&&!gt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some(s=>{var r;return((r=$t(s))==null?void 0:r.storageGroup)===e})}Ii(e,s){var r=yp[e];if(!r)return!1;var i=s[r],n=this.props[r];return he(i)&&he(n)&&n>i}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=$t(e))==null?void 0:s.storageGroup:void 0,i=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(i&&e in i)this.Pi(e,i[e]);else{if(r){var n=this.ii.H(this.yi);if(n&&e in n)return void this.Pi(e,n[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?I(this.Ai)&&(this.Ai=setTimeout(()=>{this.Ai=void 0,this.Fi()},e)):this.Fi()}}flush(){I(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,es))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var i of(this.Oi(this.ii,this.yi,s,es),nn)){var n,o=r[i];(!gt(o)||(n=this.ci[i])!=null&&n.persisted)&&this.Oi(Q,this.Si(i),o,i)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,(r,i)=>{var n,o=(n=$t(i))==null?void 0:n.storageGroup;o?s[o][i]=r:e[i]=r}),{main:e,groups:s}}Ei(e,s){if(s===es)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,(i,n)=>{var o;r[n]=(o=$t(n))!=null&&o.volatile?"__volatile__":i}),JSON.stringify(r)}Oi(e,s,r,i){var n=this.Mi(i);if(i===es||n.dirty||I(n.fingerprint)){var o;try{if((o=this.Ei(r,i))===n.fingerprint)return void(n.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(n.dirty=!1,i!==es&&(n.persisted=!0),I(o)||(n.fingerprint=o)):this.Ne.debug&&C.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(I(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var i of nn)Q.q(this.Si(i));r?delete this.ci[es]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){I(s)&&(s="None"),this.$i=I(r)?this.ji:r;var i=!1;if(Z(e,(n,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,n),i=!0)}),i)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=I(s)?this.ji:s;var r=!1;if(Z(e,(i,n)=>{e.hasOwnProperty(n)&&(this.props[n]!==i||te(i)||L(i))&&(this.Pi(n,i),r=!0)}),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var i of s)i in this.props&&(this.Ri(i),r=!0);r&&this.save()}update_campaign_params(){var e=F==null?void 0:F.URL;if(e!==this.mi){var s=Su(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);gt(Do(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=F==null?void 0:F.referrer)?ku(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Iu(),$referring_domain:F!=null&&F.referrer&&((e=ni(F.referrer))==null?void 0:e.host)||ai},void 0)}set_initial_person_info(){this.props[Kn]||this.props[Jn]||this.register_once({[Qr]:Cu(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([Jn,Kn],i=>{var n=this.props[i];n&&Z(n,function(o,a){e["$initial_"+Pn(a)]=o})});var s=this.props[Qr];if(s){var r=function(i,n){n===void 0&&(n=!1);var o=Fu(i,n),a={};return Z(o,function(l,u){a["$initial_"+Pn(u)]=l}),a}(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,function(s,r){r in e||(e[r]=s)}),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var i=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every((h,p)=>h===d[p])})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),n=i?this.bi(e):this.ii,o=this.wi(e);if(i||o!==this.pi){var a=this.props;this.clear(),this.ii=n,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,s){var r=this.props[Bs]||{};r[e]=s,this.Pi(Bs,r),this.save()}remove_event_timer(e){var s=this.props[Bs]||{},r=s[e];return I(r)||(delete s[e],this.Pi(Bs,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=$t(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=$t(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Er(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,()=>{})}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},Ps={Activation:"events",Cancellation:"cancelEvents"},an={Popover:"popover",API:"api",Widget:"widget"},pt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ln={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},eo={Popover:"popover",Inline:"inline"},bp={SHOWN:"product tour shown"},ll={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},cl=se("[RateLimiter]");class Ep{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(i=>{cl.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void cl.warn('could not rate limit - continuing. Error: "'+(i==null?void 0:i.message)+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,i;e===void 0&&(e=!1);var n=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Gn))!==null&&s!==void 0?s:{tokens:n,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>n&&(l.tokens=n);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(Gn,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!L(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,i=this.captureEventsBurstLimit,n=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+n+" events per second and "+i+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!1&&new Date().getTime()e(this.remoteConfig)):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return St.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void St.warn("Remote config is disabled. Falling back to local config.");this.Wi(e=>{if(!e)return St.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi(s=>{this.Zi(s.json,s),this.Gi()});this.Zi(e),this.Gi()})}catch(e){St.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval(()=>{this.refresh()},s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||St.warn("Failed to fetch remote config from PostHog."):St.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(i){St.error("Error applying remote config",i)}if((e==null?void 0:e.hasFeatureFlags)!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(i){St.error("Error loading feature flags",i)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,Wo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),zo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ul=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ru=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var n=s[r];s[r+1]>n;++n)i[n]=n-s[r]<<5|r;return[s,i]},Tu=Ru(Wo,2),to=Tu[1];Tu[0][28]=258,to[258]=28;for(var dl=Ru(zo,0)[1],$u=new Ae(32768),ne=0;32768>ne;++ne){var ts=(43690&ne)>>>1|(21845&ne)<<1;$u[ne]=((65280&(ts=(61680&(ts=(52428&ts)>>>2|(13107&ts)<<2))>>>4|(3855&ts)<<4))>>>8|(255&ts)<<8)>>>1}var Gs=function(t,e,s){for(var r=t.length,i=0,n=new Ae(e);r>i;++i)++n[t[i]-1];var o,a=new Ae(e);for(i=0;e>i;++i)a[i]=a[i-1]+n[i-1]<<1;for(o=new Ae(r),i=0;r>i;++i)o[i]=$u[a[t[i]-1]++]>>>15-t[i];return o},Vt=new qe(288);for(ne=0;144>ne;++ne)Vt[ne]=8;for(ne=144;256>ne;++ne)Vt[ne]=9;for(ne=256;280>ne;++ne)Vt[ne]=7;for(ne=280;288>ne;++ne)Vt[ne]=8;var li=new qe(32);for(ne=0;32>ne;++ne)li[ne]=5;var Sp=Gs(Vt,9),xp=Gs(li,5),Mu=function(t){return(t/8>>0)+(7&t&&1)},Nu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},nt=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},As=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},cn=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var i=s.length,n=s.slice();if(!i)return[new qe(0),0];if(i==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort(function(E,P){return E.f-P.f}),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(r=1;i>r;++r)n[r].s>h&&(h=n[r].s);var p=new Ae(h+1),f=so(s[c-1],p,0);if(f>e){r=0;var g=0,v=f-e,_=1<r;++r){var w=n[r].s;if(e>=p[w])break;g+=_-(1<>>=v;g>0;){var S=n[r].s;e>p[S]?g-=1<=0&&g;--r){var k=n[r].s;p[k]==e&&(--p[k],++g)}f=e}return[new qe(p),f]},so=function(t,e,s){return t.s==-1?Math.max(so(t.l,e,s+1),so(t.r,e,s+1)):e[t.s]=s},hl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,i=t[0],n=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==i&&a!=e)++n;else{if(!i&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(i),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(i);n=1,i=t[a]}return[s.subarray(0,r),e]},Rs=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},ro=function(t,e,s){var r=s.length,i=Mu(e+2);t[i]=255&r,t[i+1]=r>>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var n=0;r>n;++n)t[i+n+4]=s[n];return 8*(i+4+r)},pl=function(t,e,s,r,i,n,o,a,l,u,c){nt(e,c++,s),++i[256];for(var d=cn(i,15),h=d[0],p=d[1],f=cn(n,15),g=f[0],v=f[1],_=hl(h),w=_[0],S=_[1],k=hl(g),E=k[0],P=k[1],B=new Ae(19),x=0;w.length>x;++x)B[31&w[x]]++;for(x=0;E.length>x;++x)B[31&E[x]]++;for(var A=cn(B,7),R=A[0],M=A[1],$=19;$>4&&!R[ul[$-1]];--$);var N,J,z,H,oe=u+5<<3,pe=Rs(i,Vt)+Rs(n,li)+o,Ie=Rs(i,h)+Rs(n,g)+o+14+3*$+Rs(B,R)+(2*B[16]+3*B[17]+7*B[18]);if(pe>=oe&&Ie>=oe)return ro(e,c,t.subarray(l,l+u));if(nt(e,c,1+(pe>Ie)),c+=2,pe>Ie){N=Gs(h,p),J=h,z=Gs(g,v),H=g;var _e=Gs(R,M);for(nt(e,c,S-257),nt(e,c+5,P-1),nt(e,c+10,$-4),c+=14,x=0;$>x;++x)nt(e,c+3*x,R[ul[x]]);c+=3*$;for(var Ce=[w,E],Te=0;2>Te;++Te){var ae=Ce[Te];for(x=0;ae.length>x;++x)nt(e,c,_e[me=31&ae[x]]),c+=R[me],me>15&&(nt(e,c,ae[x]>>>5&127),c+=ae[x]>>>12)}}else N=Sp,J=Vt,z=xp,H=li;for(x=0;a>x;++x)if(r[x]>255){var me;As(e,c,N[257+(me=r[x]>>>18&31)]),c+=J[me+257],me>7&&(nt(e,c,r[x]>>>23&31),c+=Wo[me]);var ge=31&r[x];As(e,c,z[ge]),c+=H[ge],ge>3&&(As(e,c,r[x]>>>5&8191),c+=zo[ge])}else As(e,c,N[r[x]]),c+=J[r[x]];return As(e,c,N[256]),c+J[256]},kp=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ip=function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t}(),un=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Cp(t,e){e===void 0&&(e={});var s=function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=Ip[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}}(),r=t.length;s.p(t);var i,n,o,a,l,u=(a=10+((i=e).filename&&i.filename.length+1||0),l=8,function(d,h,p,f,g,v){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),S=w.subarray(f,w.length-g),k=0;if(!h||8>_)for(var E=0;_>=E;E+=65535){var P=E+65535;_>P?k=ro(S,k,d.subarray(E,P)):(S[E]=!0,k=ro(S,k,d.subarray(E,_)))}else{for(var B=kp[h-1],x=B>>>13,A=8191&B,R=(1<E;++E){var me=z(E),ge=32767&E,Je=$[me];if(M[ge]=Je,$[me]=ge,E>=Te){var At=_-E;if((Ie>7e3||Ce>24576)&&At>423){k=pl(d,S,0,H,oe,pe,_e,Ce,ae,E-ae,k),Ce=Ie=_e=0,ae=E;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,Et=0,xs=A,De=ge-Je&32767;if(At>2&&me==z(E-De))for(var Fe=Math.min(x,At)-1,hr=Math.min(32767,E),pr=Math.min(258,At);hr>=De&&--xs&&ge!=Je;){if(d[E+Ve]==d[E+Ve-De]){for(var je=0;pr>je&&d[E+je]==d[E+je-De];++je);if(je>Ve){if(Ve=je,Et=De,je>Fe)break;var fr=Math.min(De,je-2),Zt=0;for(de=0;fr>de;++de){var Xt=E-De+de+32768&32767,ks=Xt-M[Xt]+32768&32767;ks>Zt&&(Zt=ks,Je=Xt)}}}De+=(ge=Je)-(Je=M[ge])+32768&32767}if(Et){H[Ce++]=268435456|to[Ve]<<18|dl[Et];var ka=31&to[Ve],Ia=31&dl[Et];_e+=Wo[ka]+zo[Ia],++oe[257+ka],++pe[Ia],Te=E+Ve,++Ie}else H[Ce++]=d[E],++oe[d[E]]}}k=pl(d,S,!0,H,oe,pe,_e,Ce,ae,E-ae,k)}return Nu(w,0,f+Mu(k)+g)}(n=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l)),c=u.length;return function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&un(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}}(u,e),un(u,c-8,s.d()),un(u,c-4,r),u}var Fp=!!In||!!Fo,Ou="text/plain",Mr=!1,Lu=(t,e)=>{var s=t.split("#"),r=s[1],i=s[0].split("?"),n=i[0],o=i[1];if(!o)return t;var a=o.split("&").filter(l=>l.split("=")[0]!==e).join("&");return n+(a?"?"+a:"")+(r?"#"+r:"")},Ci=function(t,e,s){var r;s===void 0&&(s=!0);var i=t.split("?"),n=i[0],o=i[1],a=b({},e),l=(r=o==null?void 0:o.split("&").map(c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f}))!==null&&r!==void 0?r:[],u=function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,function(g,v){I(g)||I(v)||v==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(v),f[f.length]=p+"="+h)}),f.join(d)}(a);return u&&l.push(u),l.length>0?n+"?"+l.join("&"):n},dn=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Cp(function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(v){c[d++]=v},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Nu(c,0,d)}(ls(e)),{mtime:0});return{contentType:Ou,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var i=function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(parseInt(u,16))))}(ls(e)),n=(a=>"data="+encodeURIComponent(typeof a=="string"?a:ls(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}var o=ls(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Bu=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:Ci(t.url,{compression:xe.Base64}),encodedBody:dn(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:Lu(t.url,"compression"),encodedBody:dn(b({},t,{compression:void 0,Ji:void 0}))};try{e=dn(t)}catch(i){if($a(t.compression,ms(t.url,"compression")))return C.error("Failed to gzip request body, sending uncompressed payload",i),r();throw i}return e&&$a(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Cn(new Uint8Array(s)):ArrayBuffer.isView(s)&&Cn(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Mr=!0,r()):{url:t.url,encodedBody:e}},Du=t=>{try{return Bu(t)}catch(e){return C.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Pp=function(){var t=X(function*(e){var s=ls(e.data),r=yield function(n,o,a){return Fn.apply(this,arguments)}(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var i=yield r.arrayBuffer();return b({},e,{Ji:{contentType:Ou,body:i,estimatedSize:i.byteLength}})});return function(e){return t.apply(this,arguments)}}(),Ap=/Failed to fetch|NetworkError|Load failed/i,ju=t=>(t==null?void 0:t.name)==="TypeError"&&Ap.test((t==null?void 0:t.message)||""),Uu=t=>{var e=Du(t);if(e){var s=e.url,r=e.encodedBody,i=r??{},n=i.contentType,o=i.body,a=i.estimatedSize,l=new Headers;Z(t.headers,function(f,g){l.append(g,f)}),n&&l.append("Content-Type",n);var u=null,c=!1;if(Ca){var d=new Ca;u={signal:d.signal,timeout:setTimeout(()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))},t.timeout)}}var h=f=>{c&&(f==null?void 0:f.name)==="AbortError"||ju(f)?C.warn(f):C.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Fo(s,b({method:(t==null?void 0:t.method)||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then(f=>f.text().then(g=>{var v={statusCode:f.status,text:g};if(f.status===200)try{v.json=JSON.parse(g)}catch(_){C.error(_)}t.callback==null||t.callback(v)})).catch(h).finally(()=>u?clearTimeout(u.timeout):null)}catch(f){u&&clearTimeout(u.timeout),h(f)}}},io=t=>{try{var e,s=Bu(t),r=s.url,i=s.encodedBody,n=i??{},o=n.body,a=n.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:n.contentType});if(ke.sendBeacon(r,l))return;var u=L(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(L(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>L(t.data)?h:b({},t.data,{batch:h});return io(b({},t,{data:d(u.slice(0,c))})),void io(b({},t,{data:d(u.slice(c))}))}C.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),Uu(b({},t,{Yi:!0}))}catch(h){C.warn("Beacon send failed",h)}},fl=(t,e,s,r)=>{var i=r==="query"?e==="POST"?"sent_at":"_":void 0;return Ci(s===xe.GZipJS?Lu(t,"compression"):t,b({},i?{[i]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Nr=[];Fo&&Nr.push({transport:"fetch",method:Uu}),In&&Nr.push({transport:"XHR",method(t){var e=Du(t);if(e){var s=new In,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var i=r??{},n=i.contentType,o=i.body;Z(t.headers,function(a,l){s.setRequestHeader(l,a)}),n&&s.setRequestHeader("Content-Type",n),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Nr.push({transport:"sendBeacon",method:io});var no=3e3;class Rp{constructor(e,s){this.Xi=!0,this.tr=[],this.er=st((s==null?void 0:s.flush_interval_ms)||no,250,5e3,C.createLogger("flush interval"),no),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter(r=>r.url.indexOf("/e")===0),...s.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.lr(b({},r,{transport:"sendBeacon"}))})}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout(()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var n=s[i],o=new Date().getTime();n.data&&L(n.data)&&Z(n.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.lr(n)};for(var i in s)r()}},this.er))}lr(e){try{this.ir(e)}catch(s){C.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,s=>{var r,i=s,n=(i?i.batchKey:null)||i.url;I(e[n])&&(e[n]=b({},i,{data:[]})),(r=e[n].data)==null||r.push(i.data)}),this.tr=[],e}}var Tp=["retriesPerformedSoFar"];class $p{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!I(m)&&"onLine"in m.navigator&&(this.dr=m.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ie(m,"online",this.vr),ie(m,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=gc(e,Tp);at(s)&&(r.url=Ci(r.url,{retry_count:s})),this._instance._send_request(b({},r,{callback:i=>{if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(s??0))return void this.At(b({retriesPerformedSoFar:s},r));i.statusCode===0&&C.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(i)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))}(s),i=Date.now()+r;this.tr.push({retryAt:i,requestOptions:e});var n="Enqueued failed request for retry in "+r;navigator.onLine||(n+=" (Browser is offline)"),C.warn(n),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout(()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()},this.hr)}cr(){var e=Date.now(),s=[],r=this.tr.filter(n=>e>n.retryAt||(s.push(n),!1));if(this.tr=s,r.length>0)for(var i of r)this.retriableRequest(i.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,I(m)||(this.vr&&(m.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(m.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(b({},s,{transport:"sendBeacon"}))}catch(r){C.error(r)}}this.tr=[]}}class Mp{constructor(e){this.yr=()=>{var s,r,i,n;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+((o==null?void 0:o.clientHeight)||0),c=(o==null?void 0:o.scrollHeight)||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(i=this.br.maxContentY)!==null&&i!==void 0?i:0),this.br.maxContentHeight=Math.max(c,(n=this.br.maxContentHeight)!==null&&n!==void 0?n:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ie(m,"scroll",this.yr,{capture:!0}),ie(m,"scrollend",this.yr,{capture:!0}),ie(m,"resize",this.yr)}scrollElement(){if(!this._r)return m==null?void 0:m.document.documentElement;var e=L(this._r)?this._r:[this._r];for(var s of e){var r=m==null?void 0:m.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return m?e==="y"?m.scrollY||m.pageYOffset||m.document.documentElement.scrollTop||0:m.scrollX||m.pageXOffset||m.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var Np=t=>Cu(t==null?void 0:t.config.mask_personal_data_properties,t==null?void 0:t.config.custom_personal_data_properties,t==null?void 0:t.config.disable_capture_url_hashes);class gl{constructor(e,s,r,i){this.kr=n=>{var o=this.Sr();if(!o||o.sessionId!==n){var a={sessionId:n,props:this.Cr(this._instance)};this.Mr.register({[Vn]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=i||Np,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Vn]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?Fu(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(Do(this.getSetOnceProps()),(s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Pn(r)]=s}),e}}class qo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter(r=>r!==s)}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var i of this.Er["*"]||[])i(e,s)}constructor(){this.Er={}}}var Ts=se("[SessionId]");class ml{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var i;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new qo,this.Lr=(u,c)=>!(!at(u)||!at(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===dt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||ut,this.Nr=r||ut;var n=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*st(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Ts.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+n+"_window_id",this.Br="ph_"+n+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((i=this.Ne.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Ts.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return I(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter(s=>s!==e)}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!Re(s)&&!Re(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var i=s!==this._sessionActivityTimestamp,n=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,n&&!i||n&&this.Zr(s)||(this.Pr=s,this.Mr.register({[as]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return at(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(as):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!Re(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[as]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=at(e)?e:0,r=at(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[as];return L(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&m&&(m.removeEventListener(si,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ie(m,si,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===dt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),i=this.Jr(),n=i[1],o=i[2],a=this.Yr(),l=this.Vr(),u=at(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!n,p=n,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Ts.info("cross-tab refresh kept the session alive",{sessionId:n});var g=this.Jr();n=g[1],o=g[2]}h||f||u?(n=this.$r(),l=this.Nr(),Ts.info("new session ID generated",{sessionId:n,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=n!==p)&&(Ts.info("adopted cross-tab session id",{sessionId:n,windowId:l}),c=!0));var v=at(a)&&e&&!u?a:r,_=at(o)?o:new Date().getTime();this.Wr(l),this.Ur(n,v,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach(S=>S(n,l,w)),{sessionId:n,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout(()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()},1.1*this.sessionTimeoutMs))}}var Hu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&Na(s,e))return!0;try{var r=t==null?void 0:t.userAgentData;if(r!=null&&r.brands&&r.brands.some(i=>Na(i==null?void 0:i.brand,e)))return!0}catch{}return!!t.webdriver};function Wu(){return(Wu=X(function*(){var t=ke==null?void 0:ke.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e==null?void 0:e.model;return W(s)&&s.length>0?s:void 0}catch(r){return void C.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}})).apply(this,arguments)}var ci=function(t,e){if(!function(s){try{new RegExp(s)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function hn(t,e,s){return ls({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var zu={exact:(t,e)=>e.some(s=>t.some(r=>s===r)),is_not:(t,e)=>e.every(s=>t.every(r=>s!==r)),regex:(t,e)=>e.some(s=>t.some(r=>ci(s,r))),not_regex:(t,e)=>e.every(s=>t.every(r=>!ci(s,r))),icontains:(t,e)=>e.map(Sr).some(s=>t.map(Sr).some(r=>s.includes(r))),not_icontains:(t,e)=>e.map(Sr).every(s=>t.map(Sr).every(r=>!s.includes(r))),gt:(t,e)=>e.some(s=>{var r=parseFloat(s);return!isNaN(r)&&t.some(i=>r>parseFloat(i))}),lt:(t,e)=>e.some(s=>{var r=parseFloat(s);return!isNaN(r)&&t.some(i=>rt.toLowerCase();function qu(t,e){return!t||Object.entries(t).every(s=>{var r=s[1],i=e==null?void 0:e[s[0]];if(I(i)||Re(i))return!1;var n=[String(i)],o=zu[r.operator];return!!o&&o(r.values,n)})}var oo="custom",vl="i.posthog.com",Op=/^\/static\//;class Lp{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+vl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":oo),this.en[this.apiHost]}rn(e){if(Op.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===oo)return this.apiHost+s;var i=vl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}function Vu(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var V=se("[Surveys]"),Gu="seenSurvey_",Ku=t=>{try{var e=(s=>((r,i)=>""+Gu+function(n){return n.current_iteration&&n.current_iteration>0?n.id+"_"+n.current_iteration:n.id}(i))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){V.error("Failed to persist survey seen state",s)}},Bp=[an.Popover,an.Widget,an.API],Dp={ignoreConditions:!1,ignoreDelay:!1,displayType:eo.Popover},jp=se("[PostHog ExternalIntegrations]"),Up={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Hp{constructor(e){this._instance=e}ai(e,s){var r;(r=T.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,i=>{if(i)return jp.error("failed to load script",i);s()})}startIfEnabledOrStop(){var e=this,s=function(){var n,o,a,l=r[0],u=r[1];!u||(n=T.__PosthogExtensions__)!=null&&(n=n.integrations)!=null&&n[l]||e.ai(Up[l],()=>{var c;(c=T.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)}),!u&&(o=T.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=T.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;s()}}}class Wp{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X(function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(n){var i=s.sn.get(e.name)===e;i&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',n),i&&s.ln(e)}})()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)})}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class zp{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s==null?void 0:s.get_property(e);var r={};for(var i of e){var n=s==null?void 0:s.get_property(i);I(n)||(r[i]=n)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var _l="extensionsRemoteConfig";class qp{constructor(e){this.an=!1,this.instance=e,this.rt=C,this.un=e.hn,this.kv=new zp(e),this.onEvent=s=>Er(this.instance.on("eventCaptured",r=>{try{s({event:r.event,properties:r.properties})}catch(i){this.rt.error("Browser extension event listener failed",i)}})),this.onRemoteConfig=s=>{if(this.an)return Er(()=>{});var r=n=>{try{s(n)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},i=this.instance.dn.on(_l,r);return this.un&&r(this.un),Er(i)},this.vn=new Wp(C.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Qs))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Qs);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,i,n=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=n==null?void 0:n.sessionId)!==null&&s!==void 0?s:"",windowId:(r=n==null?void 0:n.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(i=n==null?void 0:n.sessionStartTimestamp)!==null&&i!==void 0?i:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var i=this;return X(function*(){r?i.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):i.instance.capture(e,s)})()}registerDynamicEventProperties(e){return Er(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(_l,e))}sendRequest(e,s){var r=this;return X(function*(){var i;s===void 0&&(s={});var n=r.instance.requestRouter.endpointFor((i=s.target)!==null&&i!==void 0?i:"api",e),o={method:s.method,url:s.query?Ci(n,s.query):n,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise(a=>{o.callback=a,r.instance._send_request(o)})})()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ks={},pn=0,ui=()=>{},yl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',$s="Surveys module not available",wl="sanitize_properties is deprecated. Use before_send instead",Ju="Invalid value for property_denylist config: ",Vp=["token","distinct_id",su],ns="posthog",Yu=!Fp&&(Pe==null?void 0:Pe.indexOf("MSIE"))===-1&&(Pe==null?void 0:Pe.indexOf("Mozilla"))===-1,fn=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Gh(F==null?void 0:F.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ui,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re==null?void 0:re.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(m==null||(e=m.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){C.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Yn,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:no},error_tracking:{},_onCapture:ui},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:np,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},Gp=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"]],bl=t=>{var e={};for(var s of Gp){var r=s[0],i=s[1];I(t[r])||(e[i]=t[r])}var n=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return I(o)||(I(t.strict_script_versioning)&&(n.strict_script_versioning=!!o),W(o)&&I(t.asset_host)&&(n.asset_host=o)),L(t.property_blacklist)&&(I(t.property_denylist)?n.property_denylist=t.property_blacklist:L(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:C.error(Ju+t.property_denylist)),n};class Kp{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){C.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class $e{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===dt||this.config.cookieless_mode===jt&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Kp,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new qo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=fn(),this.SentryIntegration=pp,this.sentryIntegration=r=>function(i,n){var o=wu(i,n);return{name:yu,processEvent:a=>o(a)}}(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Mp(this),this.pageViewManager=new ol(this),this.rateLimiter=new Ep(this),this.requestRouter=new Lp(this),this.consent=new ep(this),this.externalIntegrations=new Hp(this);var s=(e=$e.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,i,n)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(o),n==null||n({})},set_once:(r,i,n)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),n==null||n({})}},this.on("eventCaptured",r=>C.info('send "'+(r==null?void 0:r.event)+'"',r))}init(e,s,r){if(r&&r!==ns){var i,n=(i=Ks[r])!==null&&i!==void 0?i:new $e;return n._init(e,s,r),Ks[r]=n,Ks[ns][r]=n,n}return this._init(e,s,r)}_init(e,s,r){var i,n;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return C.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=fn(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=fn(s.defaults),u=bl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&C.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new on(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new on(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);L(h)&&h.forEach(P=>{W(P)&&this.yn.add(P)})}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Rp(P=>this.Pn(P),this.config.request_queue_config),this.Rn=new $p(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new ml(this),this.sessionPropsManager=new gl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((P,B,x)=>{(x!=null&&x.activityTimeout||x!=null&&x.sessionPastMaximumLength||x!=null&&x.crossTabAdoption)&&this.An()})),this.Fn(),this.config.__preview_deferred_init_extensions?(C.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Ln(g)},0)):(C.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&C.info("Starting in debug mode",{this:this,config:s,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(i=s.bootstrap)!=null&&i.distinctID||(s.bootstrap=b({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((n=s.bootstrap)==null?void 0:n.distinctID)!==void 0){var v=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==v&&w===Qt)this.identify(v);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==v&&w===Rt)C.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(ut()),k=s.bootstrap.isIdentifiedID?S:v;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?Rt:Qt),this.register({distinct_id:v,$device_id:k})}}if(g)this.register_once({distinct_id:vr,$device_id:null},"");else if(!this.get_distinct_id()){var E=this.config.get_device_id(ut());this.register_once({distinct_id:E,$device_id:E},""),this.persistence.set_property(He,Qt)}return ie(m,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?function(P,B){var x=P.config.segment;if(!x)return B();(function(A,R){var M=A.config.segment;if(!M)return R();var $=J=>{var z=()=>J.anonymousId()||ut();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,Rt)),R()},N=M.user();"then"in N&&Se(N.then)?N.then($):$(N)})(P,()=>{x.register((A=>{typeof Promise<"u"&&Promise.resolve||rn.warn("This browser does not have Promise support, and can not use the segment integration");var R=(M,$)=>{if(!$)return M;M.event.userId||M.event.anonymousId===A.get_distinct_id()||(rn.info("No userId set, resetting PostHog"),A.reset()),M.event.userId&&M.event.userId!==A.get_distinct_id()&&(rn.info("UserId set, identifying with PostHog"),A.identify(M.event.userId));var N=A.calculateEventProperties($,M.event.properties);return M.event.properties=Object.assign({},N,M.event.properties),M};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:M=>R(M,M.event.event),page:M=>R(M,is),identify:M=>R(M,en),screen:M=>R(M,"$screen")}})(P)).then(()=>{B()})})}(this,()=>this.On()):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==ui&&(C.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",P=>this.config._onCapture(P.event,P))),this.config.ip&&C.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return Wu.apply(this,arguments)}().then(P=>{P&&this.register({[Xi]:P})}).catch(ui),this}Fn(){var e,s,r,i,n,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=$e.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((i=this.Dn)==null||i.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading(()=>{this.dn.emit("featureFlagsReloading",!0)}),this.$n().add(this.featureFlags)):(n=(o=this.featureFlags).initialize)==null||n.call(o))}Ln(e){var s,r,i,n,o,a,l,u=performance.now(),c=b({},$e.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(i=this.logs)!==null&&i!==void 0?i:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(n=this.metrics)!==null&&n!==void 0?n:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,hp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach(h=>{h.initialize&&d.push(()=>{h.initialize==null||h.initialize()})}),d.push(()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach(p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h))}}),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout(()=>{this.qn(e,s)},0);var r=e.shift();if(r)try{r()}catch(n){C.error("Error initializing extension:",n)}}var i=Math.round(performance.now()-s);this.register_for_session({[ru]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[iu]:i}),this.config.__preview_deferred_init_extensions&&C.info("PostHog extensions initialized ("+i+"ms)")}Zi(e){var s;if(!F||!F.body)return C.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Zi(e)},500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=O(i.supportedCompression,xe.GZipJS)?xe.GZipJS:O(i.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=i.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Yn}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach(n=>n.onRemoteConfig==null?void 0:n.onRemoteConfig(e))}On(){try{this.config.loaded(this)}catch(r){C.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()},1),this.Un=new Au(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&_r(this.__request_queue,e=>this.Pn(e)),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,i,n;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(Qi),(r=this.logs)==null||r.flushLogs("sendBeacon"),(i=this.In)==null||i.unload(),(n=this.Rn)==null||n.unload()):this.zn()&&this.capture(Qi,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Yu?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(I(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,i,n,o=b({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&I(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=L(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d==null?void 0:d.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=function(v,_){return _===void 0&&(_=new Date().toISOString()),L(v)?v.map(w=>b({},w,{sent_at:_})):b({},v,{sent_at:_})}(o.data))),o.url=fl(o.url,o.method,o.compression,o.timestampMode);var p=Nr.filter(v=>!o.disableTransport||!v.transport||!o.disableTransport.includes(v.transport)),f=(i=(n=function(v,_){for(var w=0;v.length>w;w++)if(v[w].transport===h)return v[w]}(p))==null?void 0:n.method)!==null&&i!==void 0?i:p[0].method;if(!f)throw new Error("No available transport method");var g=v=>{try{f(v)}catch(_){ju(_)?C.warn(_):C.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&Jd&&typeof Promise<"u"&&!Mr?Pp(o).then(v=>{g(v)}).catch(v=>{if(Ma(v))return Mr=!0,void g(b({},o,{compression:void 0,url:fl(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return Ma(_)||w===mc})(v)&&(Mr=!0),g(o)}):f(o)})(b({},e,{callback:s=>{var r,i;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){pn++;try{var s,r=[],i=[],n=[];_r(e,a=>{if(a)if(L(s=a[0]))n.push(a);else if(Se(a))try{a.call(this)}catch(l){C.error("Error executing queued PostHog call",a,l)}else L(a)&&s==="alias"?r.push(a):L(a)&&s.indexOf("capture")!==-1&&Se(this[s])?n.push(a):i.push(a)});var o=function(a,l){_r(a,function(u){try{if(L(u[0])){var c=l;Z(u,function(d){c=c[d[0]].apply(c,d.slice(1))})}else l[u[0]].apply(l,u.slice(1))}catch(d){C.error("Error executing queued PostHog call",u,d)}})};o(r,this),o(i,this),o(n,this)}finally{pn--}}push(e){if(pn>0&&L(e)&&W(e[0])){var s=$e.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var i,n,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!I(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s==null?void 0:s.$current_url)&&(C.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||C.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=(r==null?void 0:r.timestamp)||d,p=Da(r==null?void 0:r.uuid,ut),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(Zr)===!0;r!=null&&r.$set&&!g&&(f.$set=r==null?void 0:r.$set);var v=r==null?void 0:r.$unset;v&&(f.$unset=v);var _,w,S,k=g?void 0:this.Vn(r==null?void 0:r.$set_once,e!==qa,e===en);if(k&&(f.$set_once=k),r!=null&&r._noTruncate||(n=this.config.properties_string_max_length,o=f,a=$=>W($)?$.slice(0,n):$,l=new Set,f=function $(N,J){if(N!==Object(N))return a?a(N):N;if(!l.has(N)){var z;if(l.add(N),L(N))z=[],_r(N,oe=>{z.push($(oe))});else{var H={};Z(N,(oe,pe)=>{l.has(oe)||(H[pe]=$(oe))}),z=H}return z}}(o)),f.timestamp=h,I(r==null?void 0:r.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=function($,N){N===void 0&&(N=[]);var J={},z=H=>{$[H]!==void 0&&(J[H]=$[H])};return Yd.forEach(z),N.forEach(z),J}(f.properties,Vp)),e===pt.DISMISSED||e===pt.SENT){var E=s==null?void 0:s[ln.SURVEY_ID],P=s==null?void 0:s[ln.SURVEY_ITERATION];Ku({id:E,current_iteration:P}),f.$set=b({},f.$set,{[(_={id:E,current_iteration:P},w=e===pt.SENT?"responded":"dismissed",S="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(S="$survey_"+w+"/"+_.id+"/"+_.current_iteration),S)]:!0})}else e===pt.SHOWN&&(f.$set=b({},f.$set,{[ln.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===bp.SHOWN){var B=s==null?void 0:s[ll.TOUR_TYPE];B&&(f.$set=b({},f.$set,{[ll.TOUR_LAST_SEEN_DATE+"/"+B]:new Date().toISOString()}))}var x=b({},f.properties.$set,f.$set);if(gt(x)||this.setPersonPropertiesForFlags(x),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Da(f.uuid,ut)}this.dn.emit("eventCaptured",f);var R=(i=r==null?void 0:r._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),M={method:"POST",url:R,data:f,compression:"best-available",timestampMode:(r==null?void 0:r._batchKey)==="recordings"||/\/s\/(?:\?|$)/.test(R)?"body":"capture-body",batchKey:r==null?void 0:r._batchKey,transport:r==null?void 0:r.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(M):this.In.enqueue(M),f}C.critical("This capture call is ignored due to client rate limiting.")}}else C.error("No event name provided to posthog.capture")}else C.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",s=>e(s.event,s))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new qp(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,i,n){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=n?void 0:this.persistence.remove_event_timer(e),a=b({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[su]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||An(a.distinct_id))&&C.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=function(E,P,B,x){var A,R,M,$;if(x===void 0&&(x=!1),!Pe)return{};var N,J=E?[...vs,...P||[]]:[],z=function(pr){for(var je=0;La.length>je;je++){var fr=La[je],Zt=fr[1],Xt=fr[0].exec(pr),ks=Xt&&(Se(Zt)?Zt(Xt,pr):Zt);if(ks)return ks}return["",""]}(Pe),H=z[0],oe=z[1],pe=(N=typeof navigator<"u"?navigator:void 0)!=null&&N.brave?{brave:!0}:{},Ie={};I(B)||(Ie.detectGoogleSearchApp=B);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Te=(R=navigator)==null?void 0:R.maxTouchPoints,ae=m==null||(M=m.screen)==null?void 0:M.width,me=m==null||($=m.screen)==null?void 0:$.height,ge=m==null?void 0:m.devicePixelRatio;I(Ce)||(_e.userAgentDataPlatform=Ce),I(Te)||(_e.maxTouchPoints=Te),I(ae)||(_e.screenWidth=ae),I(me)||(_e.screenHeight=me),I(ge)||(_e.devicePixelRatio=ge);var Je,At,de,Ve,Et,xs,De,Fe,hr=ee(Do({$os:H,$os_version:oe,$browser:Uc(Pe,navigator.vendor,pe,Ie),$device:Ba(Pe),$device_type:(At=Pe,de=_e,Fe=Ba(At),Fe===Sc||Fe===Ec||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Oc?ps:Fe===Zs||Fe===us||Fe===Xs||Fe===Tn?"Console":Fe===kc?"Wearable":Fe?Le:(de==null?void 0:de.userAgentDataPlatform)==="Android"&&((Ve=de==null?void 0:de.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((Et=de==null?void 0:de.screenWidth)!==null&&Et!==void 0?Et:0,(xs=de==null?void 0:de.screenHeight)!==null&&xs!==void 0?xs:0)/((De=de==null?void 0:de.devicePixelRatio)!==null&&De!==void 0?De:1)?Le:ps:"Desktop"),$timezone:Pu(),$timezone_offset:_p()}),{$current_url:tr(x?It(re==null?void 0:re.href):re==null?void 0:re.href,J,sr),$host:re==null?void 0:re.host,$pathname:re==null?void 0:re.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:gh(Pe,navigator.vendor,pe,Ie),$browser_language:al(),$browser_language_prefix:(Je=al(),typeof Je=="string"?Je.split("-")[0]:void 0),$screen_height:m==null?void 0:m.screen.height,$screen_width:m==null?void 0:m.screen.width,$viewport_height:m==null?void 0:m.innerHeight,$viewport_width:m==null?void 0:m.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(hr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),hr}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(n,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(E){a.$sdk_debug_error_capturing_properties=String(E)}if(this.requestRouter.region===oo&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||n?e!==Qi||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=ee(a,u),e===is&&F&&(a.title=F.title),!I(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),v=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],E=>{E in g&&delete v[E]});var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(E){C.error("Failed to produce browser extension event properties",E)}(a=ee({},c,g,v,b({},_,a))).$is_identified=this._isIdentified(),L(this.config.property_denylist)?Z(this.config.property_denylist,function(E){delete a[E]}):C.error(Ju+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(C.error(wl),a=S(a,e));var k=this.Zn();return a.$process_person_profile=k,k&&!n&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var i;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var n=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=ee({},n,o||{},e||{}),l=this.config.sanitize_properties;return l&&(C.error(wl),a=l(a,"$set_once")),s&&(this.mn=!0),gt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var i;(i=this.persistence)==null||i.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach(r=>this.yn.add(r)),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach(e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)}),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach(r=>s.push(r)),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,i;return(r=(i=this.featureFlags)==null?void 0:i.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s==null?void 0:s.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var i;(i=this.featureFlags)==null||i.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var i;return s===void 0&&(s=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:$s}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:$s})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:$s})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=Dp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:$s}}canRenderSurveyAsync(e,s){var r,i;return s===void 0&&(s=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:$s})}Jn(e){return!e||An(e)?(C.critical("Unique user id has not been set in posthog.identify"),!1):e===vr?(C.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(C.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return C.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),C.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Qs)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),e!==i&&e!==this.get_property(Ls)&&(this.unregister(Ls),this.register({distinct_id:e}));var n,o=(this.persistence.get_property(He)||Qt)===Qt,a=e!==i,l=!a&&o;if(a&&o)this.persistence.set_property(He,Rt),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(en,{distinct_id:e,$anon_distinct_id:i},{$set:s||{},$set_once:r||{}}),this.Sn=hn(e,s,r),(n=this.featureFlags)==null||n.setAnonymousDistinctId(i);else if(l){this.persistence.set_property(He,Rt);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=hn(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Ut)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=hn(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):C.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(L(e)?e:[e]).filter(i=>W(i)&&i.length>0);r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var i=this.getGroups(),n=i[e]!==s;if(n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},i,{[e]:s})}),n||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(qa,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),n&&!r&&this.reloadFeatureFlags()}else C.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,i,n,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),C.info("reset"),!this.__loaded)return C.uninitializedWarning("posthog.reset");var p,f=this.get_property(Qs),g=this.get_property(Xi),v=this.get_property(zt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(i=this.sessionPersistence)==null||i.clear(),this.yn.clear(),this.Qn(),I(v)||(p=this.persistence)==null||p.register({[zt]:v}),(n=this.surveys)==null||n.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,Qt),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===dt)this.register_once({distinct_id:vr,$device_id:null},"");else{var w=this.config.get_device_id(ut());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||I(g)||this.register({[Xi]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var s=this;return X(function*(){var r,i,n,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(i=s.jn)==null||i.dispose(),(n=s.sessionRecording)==null||n.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){C.error("Error while destroying feature flags",d)}}else C.uninitializedWarning("posthog.shutdown")})()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var n,o=(n=e.timestampLookBack)!==null&&n!==void 0?n:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(e,s){return e===this.get_property(Yc)?(C.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(I(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Ls,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(C.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=b({},this.config);if(te(e)){var r,i,n,o,a,l,u,c,d,h,p,f;ee(this.config,bl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new on(b({},this.config,{persistence:"sessionStorage"}),g,!1);var v=this.Cn(this.config.debug);Ge(v)&&(this.config.debug=v),Ge(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),C.info("set_config",{config:e,oldConfig:s,newConfig:b({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(i=this.featureFlags)==null||i.updateConfig==null||i.updateConfig(this.config,this.Qi()),(n=this.exceptionObserver)==null||n.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,i,n,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((n=this.sessionRecording)==null||n.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(b({},i,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:$e.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:ns;return s!==ns&&(s=ns+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===Rt||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===Rt}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===Yn&&!this._isIdentified()&>(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ls])&&((s=this.persistence)==null||(s=s.props)==null||!s[ei]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(C.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ei,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==jt)}es(){var e,s,r,i,n=this.En();return((e=this.persistence)==null?void 0:e.xi)!==n&&((r=this.persistence)==null||r.set_disabled(n)),((s=this.sessionPersistence)==null?void 0:s.xi)!==n&&((i=this.sessionPersistence)==null||i.set_disabled(n)),n&&(this.yn.clear(),this.Qn()),n}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==dt){if(this.gn()){var r,i,n,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new ml(this),this.pageViewManager=new ol(this),this.persistence&&(this.sessionPropsManager=new gl(this,this.sessionManager,this.persistence));var l,u=(n=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&n!==void 0?n:(a=$e.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==jt&&((c=this.surveys)==null||c.loadIfEnabled()),(I(e==null?void 0:e.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e==null?void 0:e.captureEventName)!==null&&d!==void 0?d:"$opt_in",e==null?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else C.warn(yl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==dt?(this.config.cookieless_mode===jt&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===jt&&(this.register({distinct_id:vr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):C.warn(yl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===dt||(this.config.cookieless_mode===jt?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?Hu(ke,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(ti,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ie(F,ti,this.kn)))}debug(e){e===!1?(m==null||m.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(m==null||m.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(C.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(s,r,i,n,o){var a=r in s&&!D(s[r]),l=i in s&&!D(s[i]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+i+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,C)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(rh),i=L(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var o of i){if(n=o(n),D(n)){var a="Event '"+e.event+"' was rejected in beforeSend function";return sh(e.event)?C.warn(a+". This can cause unexpected behavior."):C.info(a),null}n.properties&&!gt(n.properties)||C.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(n.properties&&D(n.properties[l]))return C.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return n}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ge(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}$e.__defaultExtensionClasses={},$e.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=qh(t.prototype[e[s]])}($e,["identify"]);class El{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(s-i.y)r-i.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var gn="$copy_autocapture",mn=se("[AutoCapture]");function vn(t,e){return e.length>t?e.slice(0,t)+"...":e}function Jp(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ct(e));return e}function Yp(t,e){var s,r,i=e.e,n=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ct(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Ne(h,"body")&&hu>c.length;)if(du(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ct(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,v=[],_={},w=!1,S=!1;if(Z(c,x=>{var A=Qn(x);if(Ne(x,"a")){var R=x.getAttribute("href");w=!!(A&&R&&Vs(R))&&(u?It(R):R)}O(ii(x),"ph-no-capture")&&(S=!0),v.push(function($,N,J,z,H){H===void 0&&(H=!1);var oe=$.tagName.toLowerCase(),pe={tag_name:oe};Uo.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?vn(1024,rl($)):vn(1024,er($)));var Ie=ii($);Ie.length>0&&(pe.classes=Ie.filter(function(ae){return ae!==""})),Z($.attributes,function(ae){var me;if((!vu($)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!N&&Vs(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=jo(ge).join(" ")),pe["attr__"+ae.name]=vn(1024,ae.name==="href"&&H?It(ge):ge)}});for(var _e=1,Ce=1,Te=$;Te=Jp(Te);)_e++,Te.tagName===$.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe}(x,n,o,a,u));var M=function($){if(!Qn($))return{};var N={};return Z($.attributes,function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Vs(H)&&(N[z]=H)}}),N}(x);ee(_,M)}),S)return{props:{},explicitNoCapture:S};if(o||(v[0].$el_text=Ne(t,"a")||Ne(t,"button")?rl(t):er(t)),w){var k,E;v[0].attr__href=w;var P=(k=ni(w))==null?void 0:k.host,B=m==null||(E=m.location)==null?void 0:E.host;P&&B&&P!==B&&(f=w)}return{props:ee({$event_type:i.type,$ce_version:1},l?{}:{$elements:v},{$elements_chain:(g=v,function(x){return x.map(A=>{var R,M,$="";if(A.tag_name&&($+=A.tag_name),A.attr_class)for(var N of(A.attr_class.sort(),A.attr_class))$+="."+N.replace(/"/g,"");var J=b({},A.text?{text:A.text}:{},{"nth-child":(R=A.nth_child)!==null&&R!==void 0?R:0,"nth-of-type":(M=A.nth_of_type)!==null&&M!==void 0?M:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return $r(J).sort((H,oe)=>H[0].localeCompare(oe[0])).forEach(H=>{var oe=H[1];return z[il(H[0].toString())]=il(oe.toString())}),($+=":")+$r(z).map(H=>H[0]+'="'+H[1]+'"').join("")}).join(";")}(function(x){return x.map(A=>{var R,M,$={text:(R=A.$el_text)==null?void 0:R.slice(0,400),tag_name:A.tag_name,href:(M=A.attr__href)==null?void 0:M.slice(0,2048),attr_class:up(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return $r(A).filter(N=>N[0].indexOf("attr__")===0).forEach(N=>$.attributes[N[0]]=N[1]),$})}(g)))},(s=v[0])!=null&&s.$el_text?{$el_text:(r=v[0])==null?void 0:r.$el_text}:{},f&&i.type==="click"?{$external_click_url:f}:{},_)}}var Ms=se("[ExceptionAutocapture]"),Sl=()=>{},Zp=se("[TracingHeaders]"),Mt=se("[Web Vitals]"),xl=9e5,kl="disabled",Il="lazy_loading",Ns="awaiting_config",xr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var ao="[SessionRecording]",ot=se(ao),Xp=se("[Heatmaps]");function _n(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var kr=se("[Product Tours]"),yn=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Oo))},Qp=["$set_once","$set"],Ye=se("[SiteApps]"),Cl="Error while initializing PostHog app with config id ";function ss(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class ef{constructor(e){this.ns=new qo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||(s==null?void 0:s.event)===(r==null?void 0:r.event),this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;I((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook((r,i)=>{this.on(r,i)})}register(e){var s,r;if(!I((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.ds)==null||c.add((u==null?void 0:u.event)||"")})}),(r=this._instance)!=null&&r.autocapture)){var i,n=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&n.add(l==null?void 0:l.selector)})}),(i=this._instance)==null||i.autocapture.setElementSelectors(n)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach(i=>{this.cs(s,i)&&this.ns.emit("actionCaptured",i.name)})}fs(e){this.onAction("actionCaptured",s=>e(s))}cs(e,s){if((s==null?void 0:s.steps)==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,i=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!ss(i,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var i=this.bs(e);if(i.length>0)return i.some(a=>ss(a.href,s.href,s.href_matching||"exact"));var n,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&ss((n=o.match(/(?::|")href="(.*?)"/))?n[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var i=this.bs(e);if(i.length>0)return i.some(u=>ss(u.text,s.text,s.text_matching||"exact")||ss(u.$el_text,s.text,s.text_matching||"exact"));var n,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(n=function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d}(l),o=s.text,a=s.text_matching||"exact",n.some(u=>ss(u,o,a)))}ys(e,s){var r,i;if(s==null||!s.selector)return!0;var n=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(n!=null&&n.includes(s.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e==null?void 0:e.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||qu(s.properties.reduce((r,i)=>{var n=L(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:n,operator:i.operator||"exact"},r},{}),e==null?void 0:e.properties)}}class tf{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId(r=>this.Ss(r))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&qu(e.propertyFilters,s==null?void 0:s.properties)}Ps(e,s){var r=new Map;return e.forEach(i=>{var n;(n=i.conditions)==null||(n=n[s])==null||(n=n.values)==null||n.forEach(o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}})}),r}Rs(e,s,r){var i=(r===Ps.Activation?this.ws:this.ks).get(e),n=[];return this.As(o=>{n=o.filter(a=>i==null?void 0:i.includes(a.id))}),n.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find(u=>u.name===e);return this.Is(l,s)})}register(e){var s;I((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter(r=>{var i,n;return((i=r.conditions)==null?void 0:i.actions)&&((n=r.conditions)==null||(n=n.actions)==null||(n=n.values)==null?void 0:n.length)>0});s.length!==0&&(this.Os==null&&(this.Os=new ef(this._instance),this.Os.init(),this.Os.fs(r=>{this.onAction(r)})),s.forEach(r=>{var i,n,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(n=r.conditions)!=null&&(n=n.actions)!=null&&n.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}}))}))}Fs(e){var s,r=e.filter(n=>{var o,a;return((o=n.conditions)==null?void 0:o.events)&&((a=n.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),i=e.filter(n=>{var o,a;return((o=n.conditions)==null?void 0:o.cancelEvents)&&((a=n.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});r.length===0&&i.length===0||((s=this._instance)==null||s._addCaptureHook((n,o)=>{this.onEvent(n,o)}),this.ws=this.Ps(e,Ps.Activation),this.ks=this.Ps(e,Ps.Cancellation))}onEvent(e,s){var r,i,n=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(i=s.properties)==null?void 0:i.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return n.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return n.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,s,Ps.Cancellation);l.length>0&&(n.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map(c=>c.id)}),this.Ns(l.map(c=>c.id)),l.forEach(c=>this.Bs(c.id)))}if(this.ws.has(e)){n.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,Ps.Activation);this.Hs(u.map(c=>c.id))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),i=[];for(var n of e)r&&this.Cs(n)?this.qs(n)&&this.Us(n):i.push(n);i.length>0&&(this._s=[...new Set([...this._s,...i])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter(r=>r!==e);var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter(n=>!s.has(n));var r=this.Zs(),i=r.filter(n=>!s.has(n));i.length!==r.length&&(this.Ws(i),i.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(b({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},i=!1;for(var n of Object.entries(s)){var o=n[0],a=n[1];e.includes(o)?i=!0:r[o]=a}i&&(gt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],n=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return n&&i===n?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var i=this.Zs(),n=this.Qs();i.length>0&&(this.Ws([]),i.filter(o=>he(n[o])).forEach(o=>this.Bs(o))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter(e=>!this.ea(e))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class sf extends tf{constructor(e){super(e)}Js(){return qn}Ys(){return Ar}Ms(){return Rr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var s,r;this.As(n=>{r=n.find(o=>o.id===e)});var i=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(i)&&i>0}ra(){return pt.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return V}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[qn]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Ar]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Ar)}ea(){return!1}$s(e,s){var r;this.As(n=>{r=n.find(o=>o.id===s)});var i=!r||function(n){var o;return Vu(n)&&!((o=n.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||n.schedule==="always"}(r);return i?e===pt.SHOWN?"consume":"ignore":e===pt.SHOWN?"persist":e===pt.DISMISSED||e===pt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",Fl="Disabled. Not loading surveys.",rf=m!=null&&m.location?oi(m.location.hash,"__posthog")||oi(location.hash,"state"):null,Pl="_postHogToolbarParams",Al=se("[Toolbar]"),Rl=se("[FeatureFlags]");class nf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,i)=>{var n,o,a,l;return{bootstrap:{featureFlags:(n=r.bootstrap)==null?void 0:n.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:i,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:L(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Rl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),I(e.flag_keys)||L(e.flag_keys)||Rl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Tl=se("[FeatureFlags]"),Nt=se("[FeatureFlags]",{debugEnabled:!0}),wn=`" failed. Feature flags didn't load in time.`,$l="connection_error",Ml=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Nl=t=>{var e={};for(var s of $r(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Ze=se("[Error tracking]"),Ol="Refusing to render web experiment since the viewer is a likely bot",of={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ci(e,t),not_regex:(t,e)=>!ci(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments(i=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,i.forEach(n=>{if(n.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",n.feature_flag_key," to web experiment ",n),(o=s.oa)==null||o.set(n.feature_flag_key,n));var a=s._instance.getFeatureFlag(n.feature_flag_key);W(a)&&n.variants[a]&&s.la(n.name,a,n.variants[a].transforms)}else if(n.variants)for(var l in n.variants){var u=n.variants[l];ye.ua(u,s._instance)&&s.la(n.name,l,u.transforms)}})},r)},this._instance=e,this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(Ol);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach(s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var i,n=this._instance.getFeatureFlag(s),o=(i=this.oa)==null?void 0:i.get(s);n&&o!=null&&o.variants[n]&&this.la(o.name,n,o.variants[n].transforms)}})}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e==null?void 0:e.search,"__experiment_id"),r=ms(e==null?void 0:e.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments(i=>{this.ha(parseInt(s),r,i)},!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!s)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:n=>e(n.statusCode===200&&n.json&&n.json.experiments||[])})}ha(e,s,r){var i=r.filter(n=>n.id===e);i&&i.length>0&&(ye.aa("Previewing web experiment ["+i[0].name+"] with variant ["+s+"]"),this.la(i[0].name,s,i[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var i=ye.getWindowLocation();if(i){var n,o,a,l=lu(s,i.href);return(n=e.conditions)==null||!n.url||of[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return m==null?void 0:m.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Su();if(r.utm_source){var i,n,o,a,l,u,c,d,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((n=e.conditions)==null||(n=n.utm)==null?void 0:n.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;s>i;i++)r[i-1]=arguments[i];C.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(Ol):s!=="control"?r.forEach(i=>{if(i.selector){var n;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",i);var o=(n=document)==null?void 0:n.querySelectorAll(i.selector);o==null||o.forEach(a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)})}}):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?Hu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Ot="Conversations not available yet.",Ll="console",Zu="__posthogHandledLogsRequestError",bn=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[Zu]=!0,s},Bl=t=>!!t&&typeof t=="object"&&t[Zu]===!0,Fi={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Tl,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new nf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return m&&ie(m,"online",this.Ca),this.Ra=t.registerDynamicEventProperties(()=>this.Aa()?this.fa:this.pa),this.Fa(),this.initialize()}destroy(){m==null||m.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],m==null||m.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da(()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)})}q(t){this.Da(()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)})}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ds,js,Pr,Qe]){var s=this.Oa(e);I(s)||(t[e]=s)}this.fa=t;var r=b({},t),i=this.Oa(Lt);if(i)for(var n of Object.entries(i))r["$feature/"+n[0]]=n[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(qs);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter(e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s}):[]}qa(){var t=this.Ne.flagKeys;if(!I(t))return t.filter(e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s})}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var i,n,o=(i=(n=s.bootstrap)==null?void 0:n.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter(u=>!!r[u]).reduce((u,c)=>(u[c]=r[c]||!1,u),{}),l=Object.keys(o).filter(u=>a[u]).reduce((u,c)=>(o[c]&&(u[c]=o[c]),u),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,i,n=s!=null&&s.merge&&(r=this.Oa(Lt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(i=this.Oa(js))!==null&&i!==void 0?i:{},a=b({},n,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Aa(h),variant:Ra(h),reason:void 0,metadata:I(l==null?void 0:l[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(Wn),e=this.Oa(Qe),s=this.Oa(Bt);if(!s&&!e)return t||{};var r=ee({},t||{}),i=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var n of i){var o,a,l=r[n],u=e==null?void 0:e[n],c=I(u)?(o=l==null?void 0:l.enabled)!==null&&o!==void 0&&o:!!u,d=I(u)?l==null?void 0:l.variant:typeof u=="string"?u:void 0,h=s==null?void 0:s[n],p=b({},l,{enabled:c,variant:c?d??(l==null?void 0:l.variant):void 0});c!==(l==null?void 0:l.enabled)&&(p.original_enabled=l==null?void 0:l.enabled),d!==(l==null?void 0:l.variant)&&(p.original_variant=l==null?void 0:l.variant),h&&(p.metadata=b({},l==null?void 0:l.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[n]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map(s=>{var r=t[s];return{key:s,enabled:Aa(r),variant:Ra(r),payload:Pa(e[s])}})}getFlagVariants(){var t=this.Oa(Lt),e=this.Oa(Qe);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)s[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(js),e=this.Oa(Bt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)s[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach(t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}}),this.Ba=setTimeout(()=>{this.Ha()},5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter(e=>e!==t)}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Ut)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(lt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Dt),timezone:Pu()};I(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var i=this.qa();I(i)||(s.flag_keys=i);var n=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(n?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[$l]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then(c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?$l:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var v=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));v&&g.push("quota_limited"),this.F({[Tr]:g}),v?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this.ja(p,f,{partialResponse:n}),l()}}else l()}).catch(u)}catch(c){u(c)}}}Ma(){return bu(this.Sa,3)}Ua(t){this.Sa=Eu(t,this.Sa,3,()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(t,e){var s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r==null?void 0:r.variant)!==null&&s!==void 0?s:r==null?void 0:r.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+wn)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e==null?void 0:e.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var s,r=this.getFlagVariants(),i=t in r,n=r[t],o=this.getFlagPayloads()[t],a=String(n),l=this.Oa(Pr)||void 0,u=this.Oa(qs)||void 0,c=this.Oa(Ut)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Hs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Ut]:c,[Hs]:s});else{var f,g,v,_,w,S,k,E,P,B;L(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Ut]:c},s?{[Hs]:s}:{}));var x=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Tr))!==null&&f!==void 0?f:[]];I(n)&&A.push("flag_missing");var R={$feature_flag:t,$feature_flag_response:n,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((v=this.Ne.bootstrap)==null||(v=v.featureFlagPayloads)==null?void 0:v[t])||null,$used_bootstrap_value:!this.ka};I(x==null||(_=x.metadata)==null?void 0:_.has_experiment)||(R.$feature_flag_has_experiment=x.metadata.has_experiment),I(x==null||(w=x.metadata)==null?void 0:w.version)||(R.$feature_flag_version=x.metadata.version);var M,$=(S=x==null||(k=x.reason)==null?void 0:k.description)!==null&&S!==void 0?S:x==null||(E=x.reason)==null?void 0:E.code;$&&(R.$feature_flag_reason=$),x!=null&&(P=x.metadata)!=null&&P.id&&(R.$feature_flag_id=x.metadata.id),I(x==null?void 0:x.original_variant)&&I(x==null?void 0:x.original_enabled)||(R.$feature_flag_original_response=I(x.original_variant)?x.original_enabled:x.original_variant),x!=null&&(B=x.metadata)!=null&&B.original_payload&&(R.$feature_flag_original_payload=x==null||(M=x.metadata)==null?void 0:M.original_payload),A.length&&(R.$feature_flag_error=A.join(",")),this.za(R)}else s&&this.F({[Ut]:c,[Hs]:s});if(i)return{key:t,enabled:!!n,variant:typeof n=="string"?n:void 0,payload:Pa(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+wn)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch(s=>{this.rt.error("Failed to capture feature flag call",s)})}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X(function*(){var r=s.nn;if(r){var i={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},n=s.Na();n.length&&(i.evaluation_contexts=n);var o,a=s.qa();I(a)||(i.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=(u==null?void 0:u[t])||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.rt.error("Remote config feature flag callback failed",c)}}})()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+wn),e.defaultValue;var s=this.getFeatureFlag(t,e);return I(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(e=>e!==t)}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=function(i,n,o,a,l,u){n===void 0&&(n={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Tl);var c=((P,B)=>{var x=P.flags;return x?b({},P,{featureFlags:Object.fromEntries(Object.keys(x).map(A=>{var R;return[A,(R=x[A].variant)!==null&&R!==void 0?R:x[A].enabled]})),featureFlagPayloads:Object.fromEntries(Object.keys(x).filter(A=>x[A].enabled).filter(A=>{var R;return(R=x[A].metadata)==null?void 0:R.payload}).map(A=>{var R;return[A,(R=x[A].metadata)==null?void 0:R.payload]}))}):(P.featureFlags&&B.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(i,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=i.requestId,g=i.evaluatedAt;if(L(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var v={};if(h)for(var _=0;h.length>_;_++)v[h[_]]=!0;return{[Ds]:h,[Lt]:v,[Zr]:!1}}var w=h,S=p,k=d;if(l!=null&&l.partialResponse)w=b({},n,w),S=b({},o,S),k=b({},a,k);else if(i.errorsWhileComputingFlags)if(d){var E=new Set(Object.keys(d).filter(P=>{var B;return!((B=d[P])!=null&&B.failed)}));w=b({},n,Object.fromEntries(Object.entries(w).filter(P=>E.has(P[0])))),S=b({},o,Object.fromEntries(Object.entries(S||{}).filter(P=>E.has(P[0])))),k=b({},a,Object.fromEntries(Object.entries(k||{}).filter(P=>E.has(P[0]))))}else w=b({},n,w),S=b({},o,S),k=b({},a,k);return b({[Ds]:Object.keys(Nl(w)),[Lt]:w||{},[js]:S||{},[Wn]:k||{},[Zr]:i.minimalFlagCalledEvents===!0},f?{[Pr]:f}:{},g?{[qs]:g}:{})}}(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([Qe,Bt]),this.Va(),void Nt.info("All overrides cleared");if(L(t))return this.F({[Qe]:Ml(t)}),this.Va(),void Nt.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},i=s.flags,n=s.payloads;return i&&(r[Qe]=L(i)?Ml(i):i),n&&(r[Bt]=n),Object.keys(r).length&&this.F(r),i===!1&&n===!1?this.q([Qe,Bt]):i===!1?this.q(Qe):n===!1&&this.q(Bt),this.Va(),i===!1?Nt.info("Flag overrides cleared"):i&&Nt.info("Flag overrides set",{flags:i}),void(n===!1?Nt.info("Payload overrides cleared"):n&&Nt.info("Payload overrides set",{payloads:n}))}if(t&&typeof t=="object")return this.F({[Qe]:t}),this.Va(),void Nt.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(i){this.rt.error("Error while running feature flags callback",i)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Fr)||[]).find(l=>l.flagKey===t),i={["$feature_enrollment/"+t]:e},n={$feature_flag:t,$feature_enrollment:e,$set:i};r&&(n.$early_access_feature_name=r.name),s&&(n.$feature_enrollment_stage=s);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Ds]:Object.keys(Nl(o)),[Lt]:o,[lt]:b({},this.Oa(lt)||{},i)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",n).catch(l=>{this.rt.error("Failed to capture early access feature enrollment",l)})}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,s){e===void 0&&(e=!1);var r=this.Oa(Fr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X(function*(){var r=s.nn;if(r){var i,n=e?"&"+e.map(a=>"stage="+a).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+n,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Fr]:i=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(i)}catch(a){s.rt.error("Early access feature callback failed",a)}}})()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter(s=>e[s]),flagVariants:Object.keys(e).filter(s=>e[s]).reduce((s,r)=>(s[r]=e[r],s),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach(i=>{try{i(s,r,{errorsLoading:t})}catch(n){this.rt.error("Error while running feature flags callback",n)}})}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(lt)||{},r=(t==null?void 0:t.$set)||(t!=null&&t.$set_once?{}:t),i=t==null?void 0:t.$set_once,n={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in s||(n[o]=i[o]));this.F({[lt]:b({},s,n,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=b({},this.Oa(lt)||{});t.forEach(r=>{delete s[r]}),this.F({[lt]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(lt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Dt)||{},r=b({},s);for(var i of Object.keys(t))r[i]=b({},s[i],t[i]);this.F({[Dt]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Dt)||{};this.F({[Dt]:b({},e,{[t]:{}})})}else this.q(Dt)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},af={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Ns||this.Ya===xr?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=kl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var s=m==null||(e=m.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some(r=>r.name==="visible")})(),this.Ie=()=>{var e;(F==null?void 0:F.visibilityState)==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw ot.error("started without valid sessionManager"),new Error(ao+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===dt)throw new Error(ao+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ie(F,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,F==null||F.removeEventListener==null||F.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(zt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return m&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!I(Object.assign)&&!I(Array.from);this.ro&&s?(this.no(t),ot.info("starting")):(this.Ya=kl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ns&&this.Ya!==xr&&(this.Ya=Il),T!=null&&(e=T.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=T.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=T.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,i=>{if(i)return ot.error("could not load recorder",i);this.so(t)}))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(Lo),(e=this.Mr)==null||e.unregister(Zc)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(ot.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,i=()=>{var n,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((n=this.Ne.session_recording)==null?void 0:n.sampleRate,"session_recording.sampleRate"),l=this.uo(o==null?void 0:o.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o==null?void 0:o.minimumDurationMilliseconds;r.register({[zt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:u,minimumDurationMilliseconds:I(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,version:o==null?void 0:o.version,triggerGroups:o==null?void 0:o.triggerGroups})})};i(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(i)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ns&&(this.Ya=xr,ot.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):ot.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(zt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(zt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return ot.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=T.__PosthogExtensions__)==null||!e.initSessionRecording)return ot.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[nu]:!0});var i;if(this.Ja||(this.Ja=(i=T.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===xr||this.Ya===Ns?void 0:(this.Ya=Ns,ot.info("persisted remote config is stale, requesting fresh config before starting"),void new Au(this._instance).load());this.Ya=Il,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Qc]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[Xc]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?eu:tu]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},lf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new El(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map(r=>new RegExp(r)),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map(r=>new RegExp(r)),s}yo(){if(this.isBrowserSupported()){if(m&&F){var t=s=>{s=s||(m==null?void 0:m.event);try{this.bo(s)}catch(r){mn.error("Failed to capture event",r)}};if(ie(F,"submit",t,{capture:!0}),ie(F,"change",t,{capture:!0}),ie(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||(m==null?void 0:m.event);try{this.bo(s,gn)}catch(r){mn.error("Failed to capture copy/cut event",r)}};ie(F,"copy",e,{capture:!0}),ie(F,"cut",e,{capture:!0})}}}else mn.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var s=e.autocapture_opt_out;Ge(s)&&(this.instance.persistence&&this.instance.persistence.register({[On]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach(r=>{var i=F==null?void 0:F.querySelectorAll(r);i==null||i.forEach(n=>{t===n&&s.push(r)})}),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[On],r=this.co,i=this.instance.Qi()&&!this.fo;if(Re(r)&&!Ge(s)&&!i)return!1;var n=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!n}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=sn(t);uu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&Xa(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var i=e===gn;if(r&&function(d,h,p,f,g,v){var _;if(!m||Ho(d)||p!=null&&p.url_allowlist&&!Ja(p.url_allowlist,v)||p!=null&&p.url_ignorelist&&Ja(p.url_ignorelist,v))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some(x=>h.type===x))return!1}var S=mu(d,f),k=S.parentIsUsefulElement,E=S.targetElementList;if(!function(x,A){var R=A==null?void 0:A.element_allowlist;if(I(R))return!0;var M,$=function(J){if(R.some(z=>J.tagName.toLowerCase()===z))return{v:!0}};for(var N of x)if(M=$(N))return M.v;return!1}(E,p)||!Xn(E,p==null?void 0:p.css_selector_allowlist)||Xn(E,(_=p==null?void 0:p.css_selector_ignorelist)!==null&&_!==void 0?_:ip))return!1;try{var P=m.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var B=d.tagName.toLowerCase();switch(B){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return k?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Uo.indexOf(B)>-1||d.getAttribute("contenteditable")==="true")}}(r,t,this.Ne,i,i?["copy","cut"]:void 0,this.instance)){var n=Yp(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=n.props;if(n.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===gn){var l,u=pu(m==null||(l=m.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(F==null?void 0:F.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(m==null||(e=m.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(C.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,C.info("History API monitoring stopped")}monitorHistoryChanges(){m&&m.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(m&&((e=m.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,i,n){try{if(!(i in r))return Sl;var o={next:r[i]},a=n(function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)});return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[i]=a,()=>{if(r[i]!==a)for(var l=r[i];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[i]=o.next}}catch{return Sl}})(m.history,t,r=>function(i,n,o){r.call(this,i,n,o),s.So(t)})}}So(t){try{var e,s=m==null||(e=m.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){C.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ie(m,"popstate",t),this.wo=()=>{m&&m.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Ln]),this.rageclicks=new El(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;Xp.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Ln]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){_n(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=(F==null?void 0:F.visibilityState)==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){m&&F&&(this.Po=this.cr.bind(this),ie(m,si,this.Po),this.Ro=t=>this.ke(t||(m==null?void 0:m.event)),ie(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||(m==null?void 0:m.event)),ie(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new nl(this.instance,dp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ie(F,ti,this.Oo),this.vo=!0)}Eo(){var t;m&&F&&(this.Po&&m.removeEventListener(si,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(ti,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),n=function(o,a,l){for(var u=o;u&&Ct(u)&&!Ne(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:m)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(O(a,c))return!0;u=fu(u)}return!1}(sn(t),["fixed","sticky"],i);return{x:t.clientX+(n?0:r),y:t.clientY+(n?0:s),target_fixed:n,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!Ka(t.target)&&_n(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&Xa(sn(t),this.instance.config.rageclick)&&this.Vt(b({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!Ka(t.target)&&_n(t)&&(clearTimeout(this.Do),this.Do=setTimeout(()=>{this.Vt(this.$o(t,"mousemove"))},500))}Vt(t){if(m){var e=this.Ne.disable_capture_url_hashes?It(m.location.href):m.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],i=tr(e,r,sr);this.R=this.R||{},this.R[i]||(this.R[i]=[]),this.R[i].push(t)}}cr(){this.R&&!gt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:nl,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce((s,r)=>b({},s,{["$web_vitals_"+r.name+"_event"]:b({},r),["$web_vitals_"+r.name+"_value"]:r.value}),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s==null?void 0:s.name)||D(s==null?void 0:s.value))Mt.error("Invalid metric received",s);else{var i=typeof s.navigationURL=="string"?s.navigationURL:void 0,n=this.Bo(i);if(!I(n)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+n;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),I(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=n),this.R.firstMetricTimestamp=I(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=b({},s,i?{navigationURL:n}:{},{$current_url:n,timestamp:Date.now()});I(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Mt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,i,n,o=T.__PosthogExtensions__,a=o==null?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(a==null?void 0:a[this.zo])||(this.zo==="web-vitals"&&I(a)?o==null?void 0:o.postHogWebVitalsCallbacks:void 0);if(I(l)||(s=l.onLCP,r=l.onCLS,i=l.onFCP,n=l.onINP),s&&r&&i&&n){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&n(this.jo.bind(this),u),this.vo=!0}else Mt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Un]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Hn])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:xl;return t>0&&6e4>=t?xl:t}get isEnabled(){var t=re==null?void 0:re.protocol;if(t!=="http:"&&t!=="https:")return Mt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ge(this.Wo)?this.Wo:void 0;return Ge(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Mt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Un]:s}),this._instance.persistence.register({[Hn]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=T.__PosthogExtensions__,s=this.zo,r=e==null?void 0:e.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&I(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,i=>{i?Mt.error("failed to load script",i):t()})}Bo(t){var e=t||(m==null?void 0:m.location.href);if(e){var s=this._instance.config.disable_capture_url_hashes?It(e):e,r=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return tr(s,i,sr)}Mt.error("Could not determine current URL")}}},cf={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(m&&this.isEnabled&&(s=T.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=T.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=T.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,n=T.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=i(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=n(this.captureException.bind(this)))}catch(o){Ms.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Bn]),this.Jo=new oh(b({},function(s){var r,i,n,o;return s===void 0&&(s={}),{refillRate:(r=(i=s.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(n=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&n!==void 0?n:10}}(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ms})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=b({},e,t):(I(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ms.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=T.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=T.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",r=>{if(r)return Ms.error("failed to load script",r);t()})}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Bn]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,i=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(i)?Ms.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Sh([new Rh,new jh,new $h,new Th,new Bh,new Lh,new Nh,new Dh],function(r){for(var i=arguments.length,n=new Array(i>1?i-1:0),o=1;i>o;o++)n[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` -`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=za.test(h)?h.replace(za,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of n){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return function(v){if(!v.length)return[];var _=Array.from(v);return _.reverse(),_.slice(0,50).map(w=>{return b({},w,{filename:w.filename||(S=_,S[S.length-1]||{}).filename,function:w.function||gs});var S})}(u)}}("web:javascript",Ch,Ah)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(Dn))!==null&&e!==void 0?e:[],this.el=Yr(this.il()),this.rl=new Hh(this.el)}onConfigChange(){this.el=Yr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var i=t.config;if("errorTracking"in i){var n=(e=(s=i.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=i.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=n,this._instance.persistence&&this._instance.persistence.register({[Dn]:this.Xo,[jn]:o})}}}get nl(){var t,e=!!this._instance.get_property(jn),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e==null?void 0:e.syntheticException,mechanism:{handled:e==null?void 0:e.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Ze.warn("Ignoring exception step because message must be a non-empty string");var s=function(n){if(!n)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(n).reduce((a,l)=>Uh.has(l)?(o.push(l),a):(a[l]=n[l],a),{}),droppedKeys:o}}(this.sl(e)),r=s.sanitizedProperties,i=s.droppedKeys;i.length>0&&Ze.warn("Ignoring reserved exception step fields",{droppedKeys:i}),this.rl.add(b({[Kr]:t,[Jr]:new Date().toISOString()},r))}catch(n){Ze.error("Failed to add exception step. Ignoring breadcrumb.",n)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void Ze.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void Ze.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void Ze.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(n=globalThis._posthogReleaseId)=="string"&&n.length>0?n:void 0;r&&(s.$release_id=r);try{var i=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return i&&this.rl.clear(),i}catch(o){return Ze.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Ze.error("Failed to process exception event. Ignoring this exception.",o)}var n}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(s){return Ze.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Kr]:t,[Jr]:new Date().toISOString()})}sl(t){return te(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce((s,r)=>{var i=r.type,n=r.value;return W(i)&&i.length>0&&s.$exception_types.push(i),W(n)&&n.length>0&&s.$exception_values.push(n),s},{$exception_types:[],$exception_values:[]});return this.Xo.some(s=>{var r=s.values.map(i=>{var n=zu[i.operator],o=e[i.key];if(!n||!o)return!1;var a=L(i.value)?i.value:[i.value];return a.length>0&&n(a,o)});return s.type==="OR"?r.some(Boolean):r.every(Boolean)})}catch(s){return Ze.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap(e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]}).some(e=>e.filename&&e.filename.startsWith("chrome-extension://"))}hl(t){if(t.length>0){var e,s,r,i,n=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=n[n.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&L(t)}}},uf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,r;if(this.Mr&&this.Mr.register({[Oo]:!!e.productTours}),!yn(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Us])||kr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&yn(this._instance)&&this.ai(()=>this.fl())}ai(t){var e,s;(e=T.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=T.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",r=>{r?kr.error("Could not load product tours script",r):t()})}fl(){var t;!this.vl&&(t=T.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=T.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!L(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Us];if(L(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:i=>{if(yn(this._instance)){var n=i.statusCode;if(n!==200||!i.json){var o="Product Tours API could not be loaded, status: "+n;return n===0?i.error||kr.warn(o):kr.error(o),void t([],{isLoaded:!1,error:o})}var a=L(i.json.product_tours)?i.json.product_tours:[];this.cl=a,s&&s.register({[Us]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai(()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)})}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Us)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Fi),df={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=T._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,i,n,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},gc(t,Qp),{properties:b({},t.properties,f?{$set:b({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(r=(i=t.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(n=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&n!==void 0?n:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ye.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ye.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,i,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F==null?void 0:F.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(v,_,w)=>{if(v!=null&&v[_]){var S=v[_];v[_]=w(S),c.push(()=>{v[_]=S})}},f=v=>{if(h.has(v))return v;var _=d.bl(v);return _&&h.add(_),_},g=v=>v.map(_=>typeof _=="string"?_:f(_)).filter(_=>!Re(_));return p(u,"appendChild",v=>function(_){var w=f(_);return w?v.call(this,w):_}),p(u,"insertBefore",v=>function(_,w){var S=f(_);return S?v.call(this,S,w):_}),p(u,"replaceChild",v=>function(_,w){var S=f(_);return S?v.call(this,S,w):w}),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach(v=>{p(v,"append",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))}),p(v,"prepend",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))})}),[(i=l.Element)==null?void 0:i.prototype,(n=l.CharacterData)==null?void 0:n.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach(v=>{p(v,"before",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))}),p(v,"after",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))}),p(v,"replaceWith",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];var E=g(S);return S.length&&!E.length?void 0:_.apply(this,E)})}),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",v=>function(_,w){var S=f(w);return S?v.call(this,_,S):null}),this.wl=()=>{c.forEach(v=>v()),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var s=this._l();try{var r=t(s);return e&&s(),r}catch(i){throw s(),i}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ye.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach(a=>this.xl(()=>e.processEvent==null?void 0:e.processEvent(a))),e.processedBuffer=!0),Object.values(this.apps).every(a=>a.processedBuffer||a.errored)&&((o=this.yl)==null||o.call(this))},r=!1,i=o=>{e.errored=!o,e.loaded=!0,Ye.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var n=this.xl(o=>t.init({posthog:this._instance,callback(a){o(),i(a)}}),!1).processEvent;n&&(e.processEvent=n),r=!0}catch(o){Ye.error(Cl+t.id,o),i(!1)}if(r&&e.loaded)try{s()}catch(o){Ye.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(n){try{e.xl(()=>n.processEvent==null?void 0:n.processEvent(s))}catch(o){Ye.error("Error while processing event "+t.event+" for site app "+n.id,o)}};for(var i of Object.values(this.apps))r(i)}}onRemoteConfig(t){var e,s,r,i=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",l=>this.Cl(l))):void Ye.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var n=t.config;if((r=n.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;T["__$$ph_site_app_"+u]=i._instance,(l=T.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(i._instance,c,d=>{if(d)return Ye.error(Cl+u,d)})};for(var a of n.siteApps)o()}else Ye.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},hf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(I(this.Ml)&&(this.Ml=(e=T.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),I(this.Tl)&&(this.Tl=(s=T.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=T.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=T.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",r=>{if(r)return Zp.error("failed to load script",r);t()})}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return L(t)?(L(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(L(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},pf=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return V.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return V.warn("Flags not loaded yet. Not loading surveys.");var s=L(e);this.Rl=s?e.length>0:e,V.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],s=0;slocalStorage.removeItem(i))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)V.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)V.info(Fl);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())V.info("Not loading surveys in cookieless mode without consent.");else{var t=T==null?void 0:T.__PosthogExtensions__;if(t){if(!I(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(Bo);r(this._instance,"surveys",i=>{i||!t.generateSurveys?this.$l("Could not load surveys script",i):this.Dl(t.generateSurveys,e)})}catch(i){throw this.$l("Error initializing surveys",i),i}finally{this.Al=!1}}}else V.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new sf(this._instance),V.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){V.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter(e=>e!==t)}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return V.info(Fl),t([]);var s,r=this._instance.get_property(zn);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys(()=>{},!0));typeof Promise<"u"&&this.Ll?this.Ll.then(i=>t(i.surveys,i.context)):(typeof Promise<"u"&&(this.Ll=new Promise(i=>{s=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:i=>{var n;this.Ll=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;o!==0?V.error(a):i.error||V.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=i.json.surveys||[],d=c.filter(p=>function(f){return!(!f.start_date||f.end_date)}(p)&&(Vu(p)||function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)}(p)));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(n=this._instance.persistence)==null||n.register({[zn]:c,[Xr]:Date.now()});var h={isLoaded:!0};t(c,h),s==null||s({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Xr);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e==null?void 0:e.iteration)!==null&&s!==void 0?s:null};Ku(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){V.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);V.warn("init was not called")}Hl(t){var e=null;return this.getSurveys(s=>{var r;e=(r=s.find(i=>i.id===t))!==null&&r!==void 0?r:null}),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ir};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ir};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return V.warn("init was not called"),{visible:!1,disabledReason:Ir};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(V.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise(s=>{this.getSurveys(r=>{var i,n=(i=r.find(a=>a.id===t))!==null&&i!==void 0?i:null;if(n){var o=this.zl(n);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})},e)})}renderSurvey(t,e,s){var r;if(D(this._surveyManager))V.warn("init was not called");else{var i=typeof t=="string"?this.Hl(t):t;if(i!=null&&i.id)if(Bp.includes(i.type)){var n=F==null?void 0:F.querySelector(e);if(n)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(V.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var o,a;V.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,n,s),V.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,n,s);V.warn("Survey element not found")}else V.warn("Surveys of type "+i.type+" cannot be rendered in the app");else V.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))V.warn("init was not called");else{var r=this.Hl(t);if(r){var i=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(i=b({},r,{appearance:b({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==eo.Popover&&e.initialResponses&&V.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var n=this.Ul(r);if(!n.eligible)return void V.warn("Survey is not eligible to be displayed: ",n.reason)}e.displayType!==eo.Inline?this._surveyManager.handlePopoverSurvey(i,e):this.renderSurvey(i,e.selector,e.properties)}else V.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?V.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Fi),ff={toolbar:class{constructor(t){this.instance=t}Wl(t){T.ph_toolbar_state=t}Vl(){var t;return(t=T.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),Zn(this.instance.config)||!m||!F)return!1;t=t??m.location,s=s??m.history;try{if(!e){try{m.localStorage.setItem("test","test"),m.localStorage.removeItem("test")}catch{return!1}e=m==null?void 0:m.localStorage}var r,i=rf||oi(t.hash,"__posthog")||oi(t.hash,"state"),n=i?Va(()=>JSON.parse(atob(decodeURIComponent(i))))||Va(()=>JSON.parse(decodeURIComponent(i))):null;return n&&n.action==="ph_authorize"?((r=n).source="url",r&&Object.keys(r).length>0&&(n.desiredHash?t.hash=n.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem(Pl)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=T.ph_load_toolbar||T.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Al.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(cu));if(!m||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(m.localStorage.setItem(Pl,JSON.stringify(b({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var i;this.Wl(1),(i=T.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",n=>{if(n)return Al.error("[Toolbar] Failed to load",n),void this.Wl(0);this.Wl(2),this.Zl(r)}),ie(m,"turbolinks:load",()=>{this.Wl(0),this.loadToolbar(r)})}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},gf=b({experiments:ye},Fi),mf={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;D(e)||(Ge(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||Zn(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=T==null?void 0:T.__PosthogExtensions__;if(t&&!I(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Bo);s(this._instance,"conversations",r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1})}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!Re(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Zn(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":I(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":T!=null&&T.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X(function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Ot),null)})()}getMessages(t,e){var s=this;return X(function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Ot),null)})()}markAsRead(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Ot),null)})()}getTickets(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Ot),null)})()}requestRestoreLink(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Ot),null)})()}restoreFromToken(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Ot),null)})()}restoreFromUrlToken(){var t=this;return X(function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Ot),null)})()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},vf={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=b({},this.rt,{error(){for(var r=arguments.length,i=new Array(r),n=0;r>n;n++)i[n]=arguments[n];i.some(Bl)||s.rt.error(...i)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,i;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(i=this.lu)==null||i.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),m&&ie(m,"online",this.au)}uu(t,e,s,r){var i,n=function(o,a){var l,u,c,d,h,p,f,g=(l=o==null?void 0:o.flushIntervalMs)!==null&&l!==void 0?l:3e3,v=(u=o==null?void 0:o.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o==null?void 0:o.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=I(_)?Math.max(v,2048):Math.max(v,_),S=o==null?void 0:o.resourceAttributes;return{serviceName:(d=(h=S==null?void 0:S["service.name"])!==null&&h!==void 0?h:o==null?void 0:o.serviceName)!==null&&d!==void 0?d:a==null?void 0:a.serviceNameDefault,serviceVersion:(p=S==null?void 0:S["service.version"])!==null&&p!==void 0?p:o==null?void 0:o.serviceVersion,environment:(f=S==null?void 0:S["deployment.environment"])!==null&&f!==void 0?f:o==null?void 0:o.environment,resourceAttributes:S,beforeSend:o==null?void 0:o.beforeSend,flushIntervalMs:g,maxBufferSize:v,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}((i=this._instance)==null||(i=i.config)==null?void 0:i.logs,s);return[new wh(this.hu(t,e),n,this.nu,()=>this.du(),o=>o(),void 0,r),n]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu(()=>this.tr,i=>{this.tr=i});this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu(()=>this.su,i=>{this.su=i},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Ll);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch(e=>this._u(e)),this.lu&&this.lu.flush().catch(e=>this._u(e)))}_u(t){Bl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=T==null?void 0:T.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)}):this.rt.error(Bo)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ct.LogsQueue?t():void 0,setPersistedProperty(r,i){var n;r===ct.LogsQueue&&e((n=i)!==null&&n!==void 0?n:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise(e=>{if(bu(this.Sa,3))e({kind:"fatal",error:bn(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=n=>{s||(s=!0,clearTimeout(i),e(n))},i=setTimeout(()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:bn(void 0,"logs request timed out")})},9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:n=>{var o=n.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(n.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:bn(n.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=n.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}})}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=Eu(t,this.Sa,3,()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,e=>{this.tr=e}),this.su.length>0&&this.xu(t,this.su,this.mu,Ll,e=>{this.su=e})}xu(t,e,s,r,i){if(e.length!==0){var n=e.map(a=>a.record);i([]);var o=Vc(n,qc(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,i=s.sessionStartTimestamp,n=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(i)||(e.sessionStartTimestamp=i),D(n)||(e.lastActivityTimestamp=n)}if(T!=null&&(t=T.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?It(T.location.href):T.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},_f={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new bh(this.hu(),function(r){var i,n,o,a,l,u=r==null?void 0:r.resourceAttributes;return{serviceName:(i=u==null?void 0:u["service.name"])!==null&&i!==void 0?i:r==null?void 0:r.serviceName,serviceVersion:(n=u==null?void 0:u["service.version"])!==null&&n!==void 0?n:r==null?void 0:r.serviceVersion,environment:(o=u==null?void 0:u["deployment.environment"])!==null&&o!==void 0?o:r==null?void 0:r.environment,resourceAttributes:u,beforeSend:r==null?void 0:r.beforeSend,flushIntervalMs:(a=r==null?void 0:r.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r==null?void 0:r.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}}(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch(s=>this.rt.error("PostHog metrics flush failed:",s))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise(s=>{var r=!1,i=o=>{r||(r=!0,clearTimeout(n),s(o))},n=setTimeout(()=>i({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==429&&500>a)i({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;i({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))})}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},yf=b({},Fi,af,lf,cf,uf,df,pf,hf,ff,gf,mf,vf,_f);$e.__defaultExtensionClasses=b({},yf);var Xu=function(){Y.SDK_DIST_CHANNEL="npm";var t=Ks[ns]=new $e;return function(){function e(){e.done||(e.done=!0,Yu=!1,Z(Ks,function(s){s._dom_loaded()}))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ie(F,"DOMContentLoaded",e,{capture:!1}):m&&C.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),t}();const Qu="CodeFile",ed="GeneratedCode",wf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function xt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function lo(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function bf(t={},e=0){const s=lo(t.artifactType||t.type||Qu),r=lo(t.artifactName||t.name||t.fileName||`${ed}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function td(t={},e=0){const s=xt(t),r=s.artifactType||s.type||Qu,i=s.artifactName||s.name||ed;let n=s.fileName||i;return n.endsWith(".dart")||(n+=".dart"),{id:lo(s.id)||bf({...s,artifactType:r,artifactName:i,fileName:n},e),artifactType:r,artifactName:i,fileName:n,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:sd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:rd(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:xt(s.metadata),codeType:s.codeType||wf[r]||"O"}}function sd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=xt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(xt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function rd(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=xt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function co(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function rr(t,e={}){const s=[],r=typeof t=="string"?co(t):t,n=xt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(n.artifacts)?n.artifacts:[{artifactType:n.artifactType||e.artifactType,artifactName:n.artifactName||e.artifactName,fileName:n.fileName||e.fileName,description:n.description,code:n.code||e.code||(typeof t=="string"?t:""),dependencies:n.dependencies||e.dependencies,relationships:n.relationships||e.relationships}];o.forEach((d,h)=>{!(d!=null&&d.artifactType)&&!(d!=null&&d.type)&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>td(d,h)),l=new Map(o.map((d,h)=>{var p;return[xt(d).id,(p=a[h])==null?void 0:p.id]}).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=rd(n.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:n.schemaVersion||e.schemaVersion||null,id:n.id||e.id||"bundle-current",title:n.title||n.name||e.title||"Generated artifact bundle",description:n.description||e.description||"",artifacts:a,dependencies:sd(n.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(n.deployOrder)?n.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(n.warnings)?n.warnings:[]],metadata:xt(n.metadata)}}function di(t){return rr(t).artifacts[0]||td()}function _t(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Ef(t){return ys({task:"architect",userRequest:String(t??"")})}function Sf(t){const e=_t(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function xf(t){return ys({task:"review_bundle",generatedBundle:_t(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Vo(t,e=null){const s={stage:t};return e!=null&&(s.bundle=_t(e)),s}function kf({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:i}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:_t(t),artifactBundle:_t(e),bundleReview:_t(s),userFeedback:String(i)})}function id({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:_t(t),artifactBundle:_t(e),bundleReview:_t(s),userFeedback:String(r??"")})}const Dl={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"},If=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Oe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Cf(t){return Oe(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Oe(t.filterSummary)||Oe(t.filterResults):!1}function nd(t,e=0){if(!Oe(t)||e>3)return null;if(Cf(t))return t;for(const s of If){const r=t[s];if(Oe(r)){const i=nd(r,e+1);if(i)return i}}return null}function hi(t){return Array.isArray(t)?t.some(hi):Oe(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(hi):!1}function uo(t){return Array.isArray(t)?t.some(uo):Oe(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(uo):!1}function od(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Ff(t,e){if(Oe(t))for(const[s,r]of Object.entries(t)){if(!Oe(r))continue;const i=Oe(r.categories)?r.categories:{},n=Object.entries(i).filter(([,o])=>Oe(o)&&o.matched===!0).map(([o])=>o);n.length>0?n.forEach(o=>e.add(o)):r.matched===!0&&e.add(od(s))}}function Pf(t,e){var r;if(!t)return;const s=Array.isArray(t)?t.flatMap(i=>Oe(i)?Object.entries(i):[]):Object.entries(t);for(const[i,n]of s){if(!hi(n))continue;const o=od(i),a=((r=n==null?void 0:n.raiFilterResult)==null?void 0:r.raiFilterTypeResults)||(o==="rai"?n==null?void 0:n.raiFilterTypeResults:null),l=Oe(a)?Object.entries(a).filter(([,u])=>hi(u)).map(([u])=>u):[];l.length>0?l.forEach(u=>e.add(u)):e.add(o)}}function Af(t){return Dl[t]?Dl[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function jl(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function Rf(t){const e=nd(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Ff(e.filterSummary,s),Pf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,i=e.invocationResult||null,n=uo(e.filterSummary||e.filterResults);return!r&&!n&&!["PARTIAL","FAILURE"].includes(i)?null:{kind:r?"blocked":"unavailable",invocationResult:i,matchedFilters:[...s]}}function Tf(t,e){const s=Rf(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Af))],i=s.kind==="blocked",n=new Error(i?`Safety screening blocked this pipeline step for ${jl(r)}.`:"Safety screening could not be completed. Please try again.");return n.name="ModelArmorError",n.code=i?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",n.isModelArmor=!0,n.pipelineStep=e,n.userTitle=i?"Request blocked for safety":"Safety check unavailable",n.userMessage=i?`The safety check detected ${jl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",n.retryExplanation=i?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",n.matchedFilters=s.matchedFilters,n}function $f(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Ul(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of $f(t).split(` -`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const i=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);i&&s.push(i[1])}return s}function ad(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,i,n)=>n.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(i,n,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function Hl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Mf(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=ad(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await Hl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await Hl(c)),s[o]=u,a.type==="F"){const d=Ul(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const i=new Set(Ul(e.get("lib/flutter_flow/custom_functions.dart")||"")),n={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!i.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(n)}}const Nf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),Wl={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Of=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Lf=["Struct","Record"],Bf=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>En(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } -class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>En(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const i=r[1];if(!(new RegExp(`this\\.${i}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${i}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const n of i)if(n.type==="childList")for(const o of n.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(i){const n={};return i.integrity&&(n.integrity=i.integrity),i.referrerPolicy&&(n.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?n.credentials="include":i.crossOrigin==="anonymous"?n.credentials="omit":n.credentials="same-origin",n}function r(i){if(i.ep)return;i.ep=!0;const n=s(i);fetch(i.href,n)}})();var m=typeof window<"u"?window:void 0,we=typeof globalThis<"u"?globalThis:m,ke=we==null?void 0:we.navigator,F=we==null?void 0:we.document,re=we==null?void 0:we.location,Po=we==null?void 0:we.fetch,Cn=we!=null&&we.XMLHttpRequest&&"withCredentials"in new we.XMLHttpRequest?we.XMLHttpRequest:void 0,Pa=we==null?void 0:we.AbortController,eh=we==null?void 0:we.CompressionStream,Pe=ke==null?void 0:ke.userAgent;function vc(){return!(!m||m.navigator.onLine===!1)}var Is=typeof globalThis<"u"?globalThis:m;Is&&typeof self>"u"&&(Is.self=Is),Is&&typeof File>"u"&&(Is.File=function(){});var R=m??{},Y={DEBUG:!1,LIB_VERSION:"0.5.0",LIB_NAME:"browser-common"};function Aa(t,e,s,r,i,n,o){try{var a=t[n](o),l=a.value}catch(u){return void s(u)}a.done?e(l):Promise.resolve(l).then(r,i)}function X(t){return function(){var e=this,s=arguments;return new Promise(function(r,i){var n=t.apply(e,s);function o(l){Aa(n,r,i,o,a,"next",l)}function a(l){Aa(n,r,i,o,a,"throw",l)}o(void 0)})}}function b(){return b=Object.assign?Object.assign.bind():function(t){for(var e=1;arguments.length>e;e++){var s=arguments[e];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},b.apply(null,arguments)}function _c(t,e){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;s[r]=t[r]}return s}var $a=t=>{if(typeof t!="string")return t;try{return JSON.parse(t)}catch{return t}};function Ra(t){return typeof t=="string"||t}function Ta(t){return typeof t=="string"?t:void 0}var Cs,th=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],ct=function(t){return t.AnonymousId="anonymous_id",t.DistinctId="distinct_id",t.Props="props",t.EnablePersonProcessing="enable_person_processing",t.PersonMode="person_mode",t.FeatureFlagDetails="feature_flag_details",t.FeatureFlags="feature_flags",t.FeatureFlagPayloads="feature_flag_payloads",t.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",t.BootstrapFeatureFlags="bootstrap_feature_flags",t.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",t.OverrideFeatureFlags="override_feature_flags",t.Queue="queue",t.AiQueue="ai_queue",t.LogsQueue="logs_queue",t.OptedOut="opted_out",t.SessionId="session_id",t.SessionStartTimestamp="session_start_timestamp",t.SessionLastTimestamp="session_timestamp",t.PersonProperties="person_properties",t.GroupProperties="group_properties",t.InstalledAppBuild="installed_app_build",t.InstalledAppVersion="installed_app_version",t.SessionReplay="session_replay",t.PushRegistered="push_registered",t.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",t.SurveyLastSeenDate="survey_last_seen_date",t.SurveysSeen="surveys_seen",t.Surveys="surveys",t.RemoteConfig="remote_config",t.FlagsEndpointWasHit="flags_endpoint_was_hit",t.DeviceId="device_id",t}({}),Na=function(t){return t.GZipJS="gzip-js",t.Base64="base64",t}({}),sh=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],rh=["token"],yc="NativeGzipValidationError",Fn=t=>t.length>=2&&t[0]===31&&t[1]===139,Ma=(t,e)=>t===Na.GZipJS||e===Na.GZipJS||e==="gzip",Oa=t=>!(!t||typeof t!="object")&&("name"in t?String(t.name):"")==="NotReadableError",gr=t=>{var e=new Error("Native gzip produced invalid output: "+t);throw e.name=yc,e},ih=function(){var t=X(function*(e,s){18>e.size&&gr("too-short");var r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Fn(r)&&r[2]===8||gr("invalid-header");var i=new DataView(yield e.slice(e.size-8).arrayBuffer());i.getUint32(0,!0)!==(o=>{for(var a=(()=>{if(Cs)return Cs;Cs=[];for(var c=0;256>c;c++){for(var d=c,h=0;8>h;h++)d=1&d?3988292384^d>>>1:d>>>1;Cs[c]=d>>>0}return Cs})(),l=4294967295,u=0;o.length>u;u++)l=a[255&(l^o[u])]^l>>>8;return(4294967295^l)>>>0})(s)&&gr("invalid-crc");var n=s.length>>>0;i.getUint32(4,!0)!==n&&gr("invalid-size")});return function(e,s){return t.apply(this,arguments)}}();function Pn(){return Pn=X(function*(t,e,s){e===void 0&&(e=!0);try{var r=new TextEncoder().encode(t),i=new globalThis.CompressionStream("gzip"),n=i.writable.getWriter(),o=n.write(r).then(()=>n.close()).catch(function(){var u=X(function*(c){try{yield n.abort(c)}catch{}throw c});return function(c){return u.apply(this,arguments)}}()),a=new Response(i.readable).blob(),l=(yield Promise.all([a,o]))[0];return yield ih(l,r),l}catch(u){if(s!=null&&s.rethrow)throw u;return e&&console.error("Failed to gzip compress data",u),null}}),Pn.apply(this,arguments)}var nh=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],La=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var s=t.toLowerCase();return nh.concat(e).some(r=>{var i=r.toLowerCase();return s.indexOf(i)!==-1})};function L(t,e){return t.indexOf(e)!==-1}var Ii=function(t){return t.trim()},An=function(t){return t.replace(/^\$/,"")};function wc(t){var e,s=[];return(e=JSON.stringify(t,function(r,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;s.length>0&&s[s.length-1]!==this;)s.pop();if(s.includes(i))return"[Circular]";s.push(i)}return i}}))!==null&&e!==void 0?e:"null"}var bc=Object.prototype,Ec=bc.hasOwnProperty,Ci=bc.toString,B=Array.isArray||function(t){return Ci.call(t)==="[object Array]"},Se=t=>typeof t=="function",te=t=>t===Object(t)&&!B(t),gt=t=>{if(te(t)){for(var e in t)if(Ec.call(t,e))return!1;return!0}return!1},I=t=>t===void 0,W=t=>Ci.call(t)=="[object String]",$n=t=>W(t)&&t.trim().length===0,$e=t=>t===null,D=t=>I(t)||$e(t),he=t=>Ci.call(t)=="[object Number]"&&t==t,at=t=>he(t)&&t>0,Ge=t=>Ci.call(t)==="[object Boolean]",oh=t=>t instanceof FormData,ah=t=>L(sh,t),lh=t=>L(rh,t);function Sc(t){return t===null||typeof t!="object"}function Wr(t,e){return{}.toString.call(t)==="[object "+e+"]"}function Ao(t){return typeof Event<"u"&&xc(t,Event)}function xc(t,e){try{return t instanceof e}catch{return!1}}var ch=[!0,"true",1,"1","yes"],Gi=t=>L(ch,t),uh=[!1,"false",0,"0","no"];function st(t,e,s,r,i){return e>s&&(r.warn("min cannot be greater than max."),e=s),he(t)?t>s?(r.warn(" cannot be greater than max: "+s+". Using max value instead."),s):e>t?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+s+", fallback: "+i),st(i||s,e,s,r))}class dh{constructor(e){this.tt={},this.et=e.et,this.it=st(e.bucketSize,0,100,e.rt),this.nt=st(e.refillRate,0,this.it,e.rt),this.st=st(e.refillInterval,0,864e5,e.rt)}ot(e,s){var r=Math.floor((s-e.lastAccess)/this.st);r>0&&(e.tokens=Math.min(e.tokens+r*this.nt,this.it),e.lastAccess=e.lastAccess+r*this.st)}consumeRateLimit(e){var s,r=Date.now(),i=String(e),n=this.tt[i];return n?this.ot(n,r):this.tt[i]=n={tokens:this.it,lastAccess:r},n.tokens===0||(n.tokens--,n.tokens===0&&((s=this.et)==null||s.call(this,e)),n.tokens===0)}stop(){this.tt={}}}var Le="Mobile",zr="iOS",mt="Android",ps="Tablet",kc=mt+" "+ps,Ic="iPad",Cc="Apple",Fc=Cc+" Watch",Ws="Safari",fs="BlackBerry",Pc="Samsung",Ac=Pc+"Browser",$c=Pc+" Internet",qt="Chrome",hh=qt+" OS",Rc=qt+" "+zr,$o="Internet Explorer",Tc=$o+" "+Le,Ro="Opera",ph=Ro+" Mini",To="Edge",Nc="Microsoft "+To,cs="Firefox",Mc=cs+" "+zr,Zs="Nintendo",Xs="PlayStation",us="Xbox",Oc=mt+" "+Le,Lc=Le+" "+Ws,Os="Windows",Rn=Os+" Phone",Ba="Nokia",Tn="Ouya",Bc="Generic",fh=Bc+" "+Le.toLowerCase(),Dc=Bc+" "+ps.toLowerCase(),Nn="Konqueror",jc="Oculus Browser",qr="Vivaldi",Uc="Yandex",Vr="Whale",Mn="DuckDuckGo",Hc="Pale Moon",Gr="Waterfox",zs="Brave",Wc="Google Search App",le="(\\d+(\\.\\d+)?)",Ki=new RegExp("Version/"+le),gh=new RegExp(us,"i"),mh=new RegExp(Xs+" \\w+","i"),vh=new RegExp(Zs+" \\w+","i"),No=new RegExp(fs+"|PlayBook|BB10","i"),_h={"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"},zc=function(t,e,s,r){e=e||"";var i=function(n){return n!=null&&n.brave?zs:null}(s);return i||(r!=null&&r.detectGoogleSearchApp&&L(t,"GSA/")?Wc:L(t," OPR/")&&L(t,"Mini")?ph:L(t," OPR/")?Ro:No.test(t)?fs:L(t,"IE"+Le)||L(t,"WPDesktop")?Tc:L(t,"OculusBrowser")?jc:L(t,Ac)?$c:L(t,To)||L(t,"Edg/")?Nc:L(t,qr+"/")?qr:L(t,"YaBrowser/")?Uc:L(t,Vr+"/")?Vr:L(t,Mn+"/")||L(t,"Ddg/")?Mn:L(t,"FBIOS")?"Facebook "+Le:L(t,"UCWEB")||L(t,"UCBrowser")?"UC Browser":L(t,"CriOS")?Rc:L(t,"CrMo")||L(t,qt)?qt:L(t,mt)&&L(t,Ws)?Oc:L(t,"FxiOS")?Mc:L(t.toLowerCase(),Nn.toLowerCase())?Nn:L(t,zs+"/")?zs:((n,o)=>o&&L(o,Cc)||function(a){return L(a,Ws)&&!L(a,qt)&&!L(a,mt)}(n))(t,e)?L(t,Le)?Lc:Ws:L(t,"PaleMoon/")?Hc:L(t,Gr+"/")?Gr:L(t,cs)?cs:L(t,"MSIE")||L(t,"Trident/")?$o:L(t,"Gecko")?cs:"")},yh={[Tc]:[new RegExp("rv:"+le)],[Nc]:[new RegExp(To+"?\\/"+le)],[qt]:[new RegExp("("+qt+"|CrMo)\\/"+le)],[Rc]:[new RegExp("CriOS\\/"+le)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+le)],[Ws]:[Ki],[Lc]:[Ki],[Ro]:[new RegExp("(Opera|OPR)\\/"+le)],[cs]:[new RegExp(cs+"\\/"+le)],[Mc]:[new RegExp("FxiOS\\/"+le)],[Nn]:[new RegExp("Konqueror[:/]?"+le,"i")],[fs]:[new RegExp(fs+" "+le),Ki],[Oc]:[new RegExp("android\\s"+le,"i")],[$c]:[new RegExp(Ac+"\\/"+le)],[jc]:[new RegExp("OculusBrowser\\/"+le)],[qr]:[new RegExp(qr+"\\/"+le)],[Uc]:[new RegExp("YaBrowser\\/"+le)],[Vr]:[new RegExp(Vr+"\\/"+le)],[zs]:[new RegExp(zs+"\\/"+le)],[Mn]:[new RegExp("(DuckDuckGo|Ddg)\\/"+le)],[Hc]:[new RegExp("PaleMoon\\/"+le)],[Gr]:[new RegExp(Gr+"\\/"+le)],[Wc]:[new RegExp("GSA\\/"+le)],[$o]:[new RegExp("(rv:|MSIE )"+le)],Mozilla:[new RegExp("rv:"+le)]},wh=function(t,e,s,r){var i=zc(t,e,s,r),n=yh[i];if(I(n))return null;for(var o=0;n.length>o;o++){var a=t.match(n[o]);if(a)return parseFloat(a[a.length-2])}return null},Da=[[new RegExp(us+"; "+us+" (.*?)[);]","i"),t=>[us,t&&t[1]||""]],[new RegExp(Zs,"i"),[Zs,""]],[new RegExp(Xs,"i"),[Xs,""]],[No,[fs,""]],[new RegExp(Os,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Rn,""];if(new RegExp(Le).test(e)&&!/IEMobile\b/.test(e))return[Os+" "+Le,""];var s=/Windows NT ([0-9.]+)/i.exec(e);if(s&&s[1]){var r=_h[s[1]]||"";return/arm/i.test(e)&&(r="RT"),[Os,r]}return[Os,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>t&&t[3]?[zr,[t[3],t[4],t[5]||"0"].join(".")]:[zr,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=I(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+mt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+mt+")","i"),t=>t&&t[2]?[mt,[t[2],t[3],t[4]||"0"].join(".")]:[mt,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];return t&&t[1]&&(e[1]=[t[1],t[2],t[3]||"0"].join(".")),e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[hh,""]],[/Linux|debian/i,["Linux",""]]],ja=function(t){return vh.test(t)?Zs:mh.test(t)?Xs:gh.test(t)?us:new RegExp(Tn,"i").test(t)?Tn:new RegExp("("+Rn+"|WPDesktop)","i").test(t)?Rn:/iPad/.test(t)?Ic:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?Fc:No.test(t)?fs:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(Ba,"i").test(t)?Ba:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(Le).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?mt:kc:new RegExp("(pda|"+Le+")","i").test(t)?fh:new RegExp(ps,"i").test(t)&&!new RegExp(ps+" pc","i").test(t)?Dc:""},bh=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ua(t,e){return typeof(s=t)=="string"&&bh.test(s)?t:e();var s}function It(t){return t&&t.split("#")[0]}function Mo(t,e){var s=setTimeout(t,e);return s!=null&&s.unref&&(s==null||s.unref()),s}function Ha(t,e,s){return qc.apply(this,arguments)}function qc(){return(qc=X(function*(t,e,s){var r;try{return yield Promise.race([t,new Promise((i,n)=>{r=Mo(()=>{try{s==null||s(),i()}catch(o){n(o)}},e)})])}finally{clearTimeout(r)}})).apply(this,arguments)}var Eh=t=>t instanceof Error,Vc={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},Sh=Vc.info;function Gc(t){if(Ge(t))return{boolValue:t};if(typeof t=="number")return Number.isFinite(t)?Number.isInteger(t)?{intValue:t}:{doubleValue:t}:{stringValue:String(t)};if(typeof t=="string")return{stringValue:t};if(B(t))return{arrayValue:{values:t.map(e=>Gc(e))}};try{return{stringValue:JSON.stringify(t)}}catch{return{stringValue:String(t)}}}function Kr(t){var e=[];for(var s in t){var r=t[s];$e(r)||I(r)||e.push({key:s,value:Gc(r)})}return e}function xh(t,e){var s=Vc[t.level||"info"]||Sh,r=s.text,i=s.number,n=String(Date.now())+"000000",o={};e.distinctId&&(o.posthogDistinctId=e.distinctId),e.sessionId&&(o.sessionId=e.sessionId),e.windowId&&(o["window.id"]=e.windowId),D(e.sessionStartTimestamp)||(o.sessionStartTimestamp=String(e.sessionStartTimestamp)),D(e.lastActivityTimestamp)||(o.lastActivityTimestamp=String(e.lastActivityTimestamp)),e.currentUrl&&(o["url.full"]=e.currentUrl),e.screenName&&(o["screen.name"]=e.screenName),e.appState&&(o["app.state"]=e.appState),e.activeFeatureFlags&&e.activeFeatureFlags.length>0&&(o.feature_flags=e.activeFeatureFlags);var a=b({},o,t.attributes||{}),l={timeUnixNano:n,observedTimeUnixNano:n,severityNumber:i,severityText:r,body:{stringValue:t.body},attributes:Kr(a)};return t.trace_id&&(l.traceId=t.trace_id),t.span_id&&(l.spanId=t.span_id),I(t.trace_flags)||(l.flags=t.trace_flags),l}function Kc(t,e,s){return b({},t.resourceAttributes,{"service.name":t.serviceName||"unknown_service"},t.environment&&{"deployment.environment":t.environment},t.serviceVersion&&{"service.version":t.serviceVersion},{"telemetry.sdk.name":e,"telemetry.sdk.version":s})}function Jc(t,e,s,r){return{resourceLogs:[{resource:{attributes:Kr(e)},scopeLogs:[{scope:{name:s,version:r},logRecords:t}]}]}}let kh=class{constructor(t,e,s,r,i,n,o){var a;n===void 0&&(n=()=>Promise.resolve()),this._instance=t,this.Ne=e,this.rt=s,this.ut=r,this.ht=i,this.dt=n,this.vt=o,this.ct=null,this.ft=0,this.yt=0,this.bt=0,this._t=0,this.wt=!1,this.kt=e.maxBufferSize,this.xt=Math.max((a=e.maxQueueSize)!==null&&a!==void 0?a:e.maxBufferSize,e.maxBufferSize),this.St=e.flushIntervalMs,this.Ct=e.maxBatchRecordsPerPost,this.Mt=e.rateCapWindowMs,this.Tt=e.maxLogsPerInterval}reset(){this.Et(),this.ct=null,this.bt=0,this._t=0,this.wt=!1,this.ft=0,this.yt=0,this.Ct=this.Ne.maxBatchRecordsPerPost}onReconnect(){this.yt=0,this.It()}captureLog(t){if(!this._instance.isDisabled&&!this._instance.optedOut&&t!=null&&t.body){var e=this.Pt(t);if(e!==null)if(e.body){if(this.Rt()){var s={record:xh(e,this.ut())};this.ht(()=>this.At(s))}}else this.rt.info("Log was rejected in beforeSend function")}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=B(e)?e:[e],r=t;for(var i of s)try{var n=i(r);if(!n)return this.rt.info("Log was rejected in beforeSend function"),null;r=n}catch(o){return this.rt.error("Error in beforeSend function for log:",o),null}return r}Rt(){if(this.Tt===void 0)return!0;var t=Date.now(),e=t-this.bt;return this.Mt>e&&e>=0||(this.bt=t,this._t=0,this.wt=!1),this.Tt>this._t?(this._t++,!0):(this.wt||(this.rt.warn("captureLog dropping logs: exceeded "+this.Tt+" logs per "+this.Mt+"ms"),this.wt=!0),!1)}flush(){var t=this;return X(function*(){if(!t._instance.isDisabled)return t.ct||(t.ct=t.Ft().finally(()=>{t.ct=null})),t.ct})()}Ft(){var t=this;return X(function*(){var e;t.Et();var s=(e=t._instance.getPersistedProperty(ct.LogsQueue))!==null&&e!==void 0?e:[];if(s.length!==0)for(var r=s.length,i=0;s.length>0&&r>i;){var n,o;t.ft=0;var a=Math.min(s.length,t.Ct),l=s.slice(0,a),u=Jc(l.map(d=>d.record),t.Lt(),(n=t.vt)!==null&&n!==void 0?n:t._instance.getLibraryId(),t._instance.getLibraryVersion()),c=yield t._instance.Ot(u);if(c.kind==="too-large"&&l.length>1)t.Ct=Math.max(1,Math.floor(l.length/2)),t.rt.warn("Received 413 when sending logs batch of size "+l.length+", reducing batch size to "+t.Ct);else if(c.kind==="retry-later"||(c.kind==="too-large"?t.rt.warn("Dropping a single log record after 413 with batch size 1 — the record is larger than the server cap and cannot be split further."):c.kind==="ok"&&t.Ne.maxBatchRecordsPerPost>t.Ct&&(t.Ct=Math.min(t.Ne.maxBatchRecordsPerPost,t.Ct+1)),yield t.Dt(l.length),s=(o=t._instance.getPersistedProperty(ct.LogsQueue))!==null&&o!==void 0?o:[],i+=l.length,c.kind==="fatal"))throw c.error}})()}Dt(t){var e=this;return X(function*(){var s,r=Math.max(0,t-e.ft),i=(s=e._instance.getPersistedProperty(ct.LogsQueue))!==null&&s!==void 0?s:[];e._instance.setPersistedProperty(ct.LogsQueue,i.slice(r)),yield e.dt()})()}Lt(){return Kc(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion())}At(t){var e;if(!this._instance.optedOut){var s=(e=this._instance.getPersistedProperty(ct.LogsQueue))!==null&&e!==void 0?e:[];this.xt>s.length||(s.shift(),this.ft++,this.rt.info("Logs queue is full, dropping oldest record.")),s.push(t),this._instance.setPersistedProperty(ct.LogsQueue,s),this.kt>s.length?this.$t():this.It()}}$t(t){t===void 0&&(t=this.St),this.Nt||(this.Nt=Mo(()=>{this.Nt=void 0,this.It()},t))}qt(){var t=Math.min(Math.max(0,this.yt-1),6);return this.St*Math.pow(2,t)}jt(){var t=this._instance.getPersistedProperty(ct.LogsQueue);return!!t&&t.length>0}shutdown(t){var e=this;return X(function*(){e.Et();var s=e.flush().catch(()=>{});t!==void 0?yield Ha(s,t):yield s})()}flushWithTimeout(t){var e=this;return X(function*(){var s=e.flush();yield Ha(s,t,()=>{s.catch(()=>{})})})()}It(){this.flush().then(()=>{this.yt=0},t=>{this.yt++,this.rt.error("PostHog logs flush failed:",t)}).finally(()=>{!this._instance.isDisabled&&this.jt()&&this.$t(this.qt())})}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}};var Ji=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function Wa(t){return String(t)+"000000"}function za(t,e,s,r){var i="";return r&&(i=Object.keys(r).sort().map(n=>JSON.stringify(n)+":"+JSON.stringify(r[n])).join(",")),t+"\0"+e+"\0"+(s??"")+"\0"+i}let Ih=class{constructor(t,e,s){this._instance=t,this.Ne=e,this.rt=s,this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Wt=0}count(t,e,s){e===void 0&&(e=1),this.Vt({name:t,type:"count",value:e,unit:s==null?void 0:s.unit,attributes:s==null?void 0:s.attributes})}gauge(t,e,s){this.Vt({name:t,type:"gauge",value:e,unit:s==null?void 0:s.unit,attributes:s==null?void 0:s.attributes})}histogram(t,e,s){this.Vt({name:t,type:"histogram",value:e,unit:s==null?void 0:s.unit,attributes:s==null?void 0:s.attributes})}flush(){var t=this,e=this.ct,s=function(){var i=X(function*(){e&&(yield e.catch(()=>{})),yield t.Zt()});return function(){return i.apply(this,arguments)}}(),r=s().finally(()=>{this.ct===r&&(this.ct=null)});return this.ct=r,r}drainWindow(){if(this.Bt.size===0)return null;var t=this.Bt;return this.Bt=new Map,this.Ht=!1,this.Ut=new Map,this.zt=new Set,this.Gt(t)}reset(){this.Wt++,this.Et(),this.Bt=new Map,this.ct=null,this.Ht=!1,this.Ut=new Map,this.zt=new Set}Vt(t){if(!this._instance.isDisabled&&!this._instance.optedOut){var e=this.Pt(t);if(e!==null)if(e.name&&typeof e.name=="string")if(typeof e.value=="number"&&Number.isFinite(e.value))if(e.type==="count"&&0>e.value)this.rt.warn("Dropping count '"+e.name+"': counters are monotonic, value must be >= 0");else{var s,r;try{s=e.attributes?b({},e.attributes):void 0,r=za(e.type,e.name,e.unit,s)}catch(o){return void this.rt.warn("Dropping metric '"+e.name+"': attributes could not be serialized",o)}var i=this.Bt.get(r);if(!i){if(!this.Qt())return;i={name:e.name,type:e.type,unit:e.unit,attributes:s,windowStartMs:Date.now()},this.Bt.set(r,i)}var n=this.Ut.get(e.name);n===void 0?this.Ut.set(e.name,e.type):n===e.type||this.zt.has(e.name)||(this.zt.add(e.name),this.rt.warn("Metric name '"+e.name+"' is already used as a "+n+"; recording it as a "+e.type+" too will blend both series in charts. Use a distinct name.")),this.Kt(i,e.value),this.$t()}else this.rt.warn("Dropping metric '"+e.name+"': value must be a finite number");else this.rt.warn("Dropping metric with empty name")}}Qt(){return this.Ne.maxSeriesPerFlush>this.Bt.size||(this.Ht||(this.Ht=!0,this.rt.warn("Metric series cap reached ("+this.Ne.maxSeriesPerFlush+" per flush window); dropping new series until the next flush. Reduce attribute cardinality.")),!1)}Kt(t,e){var s;switch(t.type){case"count":t.total=((s=t.total)!==null&&s!==void 0?s:0)+e;break;case"gauge":t.last=e;break;case"histogram":t.hist||(t.hist={count:0,sum:0,min:e,max:e,bucketCounts:new Array(Ji.length+1).fill(0)});var r=t.hist;r.count+=1,r.sum+=e,r.min=Math.min(r.min,e),r.max=Math.max(r.max,e),r.bucketCounts[function(i,n){for(var o=0;n.length>o;o++)if(n[o]>=i)return o;return n.length}(e,Ji)]+=1}}Pt(t){var e=this.Ne.beforeSend;if(!e)return t;var s=B(e)?e:[e],r=t;for(var i of s)try{var n=i(r);if(!n)return this.rt.info("Metric was rejected in beforeSend function"),null;r=n}catch(o){return this.rt.error("Error in beforeSend function for metric:",o),null}return r}$t(){this.Nt||(this.Nt=Mo(()=>{this.Nt=void 0,this.flush().catch(t=>{this.rt.error("Metrics flush failed:",t)})},this.Ne.flushIntervalMs))}Et(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0)}Zt(){var t=this;return X(function*(){if(t.Bt.size!==0){var e=t.Bt;t.Bt=new Map,t.Ht=!1,t.Ut=new Map,t.zt=new Set;var s=t.Wt,r=yield t._instance.Jt(t.Gt(e));if(s===t.Wt)switch(r.kind){case"ok":return;case"retry-later":return t.Yt(e),void t.$t();case"too-large":return void t.rt.warn("Metrics batch exceeded the server size limit and was dropped");case"fatal":return void t.rt.error("Failed to send metrics batch:",r.error)}}})()}Gt(t){return e=this.Xt(t),s=function(n,o,a){return b({},n.resourceAttributes,{"service.name":n.serviceName||"unknown_service"},n.environment&&{"deployment.environment":n.environment},n.serviceVersion&&{"service.version":n.serviceVersion},{"telemetry.sdk.name":o,"telemetry.sdk.version":a})}(this.Ne,this._instance.getLibraryId(),this._instance.getLibraryVersion()),r=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:Kr(s)},scopeMetrics:[{scope:{name:r,version:i},metrics:e}]}]};var e,s,r,i}Xt(t){var e=Wa(Date.now()),s=new Map;for(var r of t.values()){var i,n=za(r.type,r.name,r.unit,void 0),o=s.get(n);o||(o=b({name:r.name},r.unit&&{unit:r.unit}),r.type==="count"?o.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:r.type==="gauge"?o.gauge={dataPoints:[]}:o.histogram={aggregationTemporality:1,dataPoints:[]},s.set(n,o));var a=Kr((i=r.attributes)!==null&&i!==void 0?i:{}),l=Wa(r.windowStartMs);if(r.type==="count"){var u,c={attributes:a,startTimeUnixNano:l,timeUnixNano:e,asDouble:(u=r.total)!==null&&u!==void 0?u:0};o.sum.dataPoints.push(c)}else if(r.type==="gauge"){var d,h={attributes:a,timeUnixNano:e,asDouble:(d=r.last)!==null&&d!==void 0?d:0};o.gauge.dataPoints.push(h)}else r.hist&&o.histogram.dataPoints.push({attributes:a,startTimeUnixNano:l,timeUnixNano:e,count:r.hist.count,sum:r.hist.sum,min:r.hist.min,max:r.hist.max,bucketCounts:r.hist.bucketCounts,explicitBounds:Ji})}return Array.from(s.values())}Yt(t){var e,s;for(var r of t){var i=r[0],n=r[1],o=this.Bt.get(i);if(o)switch(o.windowStartMs=Math.min(o.windowStartMs,n.windowStartMs),o.type){case"count":o.total=((e=o.total)!==null&&e!==void 0?e:0)+((s=n.total)!==null&&s!==void 0?s:0);break;case"gauge":break;case"histogram":if(n.hist)if(o.hist){o.hist.count+=n.hist.count,o.hist.sum+=n.hist.sum,o.hist.min=Math.min(o.hist.min,n.hist.min),o.hist.max=Math.max(o.hist.max,n.hist.max);for(var a=0;o.hist.bucketCounts.length>a;a++)o.hist.bucketCounts[a]+=n.hist.bucketCounts[a]}else o.hist=n.hist}else this.Qt()&&this.Bt.set(i,n)}}};var mr,qa,Yi;function Ch(t){var e=globalThis._posthogChunkIds;if(e){var s=Object.keys(e);return Yi&&s.length===qa||(qa=s.length,Yi=s.reduce((r,i)=>{mr||(mr={});var n=mr[i];if(n)r[n[0]]=n[1];else for(var o=t(i),a=o.length-1;a>=0;a--){var l=o[a],u=l==null?void 0:l.filename,c=e[i];if(u&&c){r[u]=c,mr[i]=[u,c];break}}return r},{})),Yi}}class Fh{constructor(e,s,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=s,this.modifiers=r}buildFromUnknown(e,s){s===void 0&&(s={});var r=s&&s.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,s,0).apply(e),n=this.buildParsingContext(s),o=this.parseStacktrace(i,n);return{$exception_list:this.convertToExceptionList(o,r),$exception_level:"error"}}modifyFrames(e){var s=this;return X(function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&B(r.stacktrace.frames)&&(r.stacktrace.frames=yield s.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var s;return{type:"Error",value:"Unknown error",stack:(s=e.syntheticException)==null?void 0:s.stack,synthetic:!0}}parseStacktrace(e,s){var r,i;return e.cause!=null&&(r=this.parseStacktrace(e.cause,s)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?s.skipFirstLines:0),s.chunkIdMap)),b({},e,{cause:r,stack:i})}applyChunkIds(e,s){return e.map(r=>(r.filename&&s&&(r.chunk_id=s[r.filename]),r))}applyCoercers(e,s){for(var r of this.coercers)if(r.match(e))return r.coerce(e,s);return this.coerceFallback(s)}applyModifiers(e){var s=this;return X(function*(){var r=e;for(var i of s.modifiers)r=yield i(r);return r})()}convertToExceptionList(e,s){var r,i,n,o={type:e.type,value:e.value,mechanism:{type:(r=s.type)!==null&&r!==void 0?r:"generic",handled:(i=s.handled)===null||i===void 0||i,synthetic:(n=e.synthetic)!==null&&n!==void 0&&n}};e.stack&&(o.stacktrace={type:"raw",frames:e.stack});var a=[o];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,b({},s,{handled:!0}))),a}buildParsingContext(e){var s;return{chunkIdMap:Ch(this.stackParser),skipFirstLines:(s=e.skipFirstLines)!==null&&s!==void 0?s:1}}buildCoercingContext(e,s,r){r===void 0&&(r=0);var i=(n,o)=>{if(4>=o){var a=this.buildCoercingContext(e,s,o);return this.applyCoercers(n,a)}};return b({},s,{syntheticException:r==0?s.syntheticException:void 0,mechanism:e,apply:n=>i(n,r),next:n=>i(n,r+1)})}}var gs="?";function On(t,e,s,r,i){var n={platform:t,filename:e,function:s===""?gs:s,in_app:!0};return I(r)||(n.lineno=r),I(i)||(n.colno=i),n}var Yc=(t,e)=>{var s=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return s||r?[t.indexOf("@")!==-1?t.split("@")[0]:gs,s?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},Ph=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Ah=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,$h=/\((\S*)(?::(\d+))(?::(\d+))\)/,Rh=(t,e)=>{var s=Ph.exec(t);if(s)return On(e,s[1],gs,+s[2],+s[3]);var r=Ah.exec(t);if(r){if(r[2]&&r[2].indexOf("eval")===0){var i=$h.exec(r[2]);i&&(r[2]=i[1],r[3]=i[2],r[4]=i[3])}var n=Yc(r[1]||gs,r[2]);return On(e,n[1],n[0],r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}},Th=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Nh=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Mh=(t,e)=>{var s=Th.exec(t);if(s){if(s[3]&&s[3].indexOf(" > eval")>-1){var r=Nh.exec(s[3]);r&&(s[1]=s[1]||"eval",s[3]=r[1],s[4]=r[2],s[5]="")}var i=s[3],n=s[1]||gs,o=Yc(n,i);return On(e,i=o[1],n=o[0],s[4]?+s[4]:void 0,s[5]?+s[5]:void 0)}},Va=/\(error: (.*)\)/;class Oh{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,s){var r=W(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var s=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?s+": "+e.message:s}isDOMException(e){return Wr(e,"DOMException")}isDOMError(e){return Wr(e,"DOMError")}}class Lh{match(e){return function(s){switch({}.toString.call(s)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return xc(s,Error)}}(e)}coerce(e,s){return{type:this.getType(e),value:this.getMessage(e,s),stack:this.getStack(e),cause:e.cause?s.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,s){var r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){return e.stacktrace||e.stack||void 0}}class Bh{constructor(){}match(e){return!!Wr(e,"ErrorEvent")&&(e.error!=null||this.fe(e))}coerce(e,s){var r;if(e.error!=null)return s.apply(e.error);var i=s.apply(e.message);return b({},i,{stack:(r=this.pe(e))!==null&&r!==void 0?r:i.stack,synthetic:!0})}fe(e){return W(e.message)&&e.message.length>0}pe(e){var s=e;if(W(s.filename)&&s.filename.length>0){var r,i,n=(r=s.lineno)!==null&&r!==void 0?r:0,o=(i=s.colno)!==null&&i!==void 0?i:0;return`Error + at `+s.filename+":"+n+":"+o}}}var Dh=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class jh{match(e){return typeof e=="string"}coerce(e,s){var r,i=this.getInfos(e),n=i[0],o=i[1];return{type:n??"Error",value:o??e,stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var s="Error",r=e,i=e.match(Dh);return i&&(s=i[1],r=i[2]),[s,r]}}var Uh=["fatal","error","warning","log","info","debug"];function Zc(t,e){e===void 0&&(e=40);var s=Object.keys(t);if(s.sort(),!s.length)return"[object has no keys]";for(var r=s.length;r>0;r--){var i=s.slice(0,r).join(", ");if(e>=i.length)return r===s.length?i:i.length>e?i.slice(0,e)+"...":i}return""}class Hh{match(e){return typeof e=="object"&&e!==null}coerce(e,s){var r,i,n=this.getErrorPropertyFromObject(e);return n?s.apply(n):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(i=s.syntheticException)==null?void 0:i.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return Ao(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var s="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(s+=" with message: '"+e.message+"'"),s}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+Zc(e)}isSeverityLevel(e){return W(e)&&!$n(e)&&Uh.indexOf(e)>=0}getStack(e){try{return W(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:W(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(var s in e)if({}.hasOwnProperty.call(e,s)){var r=e[s];if(Eh(r))return r}}getObjectClassName(e){try{var s=Object.getPrototypeOf(e);return s?s.constructor.name:void 0}catch{return}}}class Wh{match(e){return Ao(e)}coerce(e,s){var r,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+Zc(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class zh{match(e){return Sc(e)}coerce(e,s){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class qh{match(e){return Wr(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!Ao(e))return!1;try{var s=e.detail;return s!=null&&typeof s=="object"&&"reason"in s}catch{return!1}}coerce(e,s){var r,i=this.getUnhandledRejectionReason(e);return Sc(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=s.syntheticException)==null?void 0:r.stack,synthetic:!0}:s.apply(i)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}}var Jr="$message",Yr="$timestamp",Vh=new Set([Jr,Yr]),Zi={enabled:!0,max_bytes:32768};function Zr(t){var e;return t?{enabled:(e=t.enabled)!==null&&e!==void 0?e:Zi.enabled,max_bytes:Kh(t.max_bytes,Zi.max_bytes)}:b({},Zi)}class Gh{constructor(e){this.Ke=[],this.Je=0,this.Ne=Zr(e)}setConfig(e){this.Ne=Zr(e),this.Xe()}add(e){var s=function(i){var n;try{n=wc(i)}catch{return}try{var o=JSON.parse(n);if(!te(o))return;var a=o,l=a[Jr],u=a[Yr];return!W(l)||l.trim().length===0||!W(u)&&!he(u)?void 0:{step:a,json:n}}catch{return}}(e);if(s){var r=function(i){if(typeof TextEncoder<"u")return new TextEncoder().encode(i).length;for(var n=encodeURIComponent(i),o=0,a=0;n.length>a;a++)n[a]==="%"?(o+=1,a+=2):o+=1;return o}(s.json);r>this.Ne.max_bytes||(this.Ke.push({step:s.step,bytes:r}),this.Je+=r,this.Xe())}}getAttachable(){return this.Ke.map(e=>e.step)}clear(){this.Ke=[],this.Je=0}size(){return this.Ke.length}Xe(){for(;this.Je>this.Ne.max_bytes&&this.Ke.length>0;){var e=this.Ke.shift();e&&(this.Je-=e.bytes)}}}function Kh(t,e){if(!he(t)||t===1/0||t===-1/0)return e;var s=Math.floor(t);return 0>s?e:s}var Xc=function(t,e){var s=(e===void 0?{}:e).debugEnabled,r={k(i){if(m&&(Y.DEBUG||m.POSTHOG_DEBUG||s)&&!I(m.console)&&m.console){for(var n=("__rrweb_original__"in m.console[i])?m.console[i].__rrweb_original__:m.console[i],o=arguments.length,a=new Array(o>1?o-1:0),l=1;o>l;l++)a[l-1]=arguments[l];n(t,...a)}},debug(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("debug",...n)},info(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("log",...n)},warn(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("warn",...n)},error(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];r.k("error",...n)},critical(){for(var i=arguments.length,n=new Array(i),o=0;i>o;o++)n[o]=arguments[o];console.error(t,...n)},uninitializedWarning(i){r.error("You must initialize PostHog before calling "+i)},createLogger:(i,n)=>Xc(t+" "+i,n)};return r},C=Xc("[PostHog.js]"),se=C.createLogger,Jh=se("[ExternalScriptsLoader]"),Xi=(t,e,s)=>{if(t.config.disable_external_dependency_loading)return Jh.warn(e+" was requested but loading of external scripts is disabled."),s("Loading of external scripts is disabled");var r=F==null?void 0:F.querySelectorAll("script");if(r){for(var i,n=function(){if(r[o].src===e){var l=r[o];return l.__posthog_loading_callback_fired?{v:s()}:(l.addEventListener("load",u=>{l.__posthog_loading_callback_fired=!0,s(void 0,u)}),l.onerror=u=>s(u),{v:void 0})}},o=0;r.length>o;o++)if(i=n())return i.v}var a=()=>{if(!F)return s("document not found");var l=F.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=d=>{l.__posthog_loading_callback_fired=!0,s(void 0,d)},l.onerror=d=>s(d),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return s("prepare_external_dependency_script returned null");if(t.config.external_scripts_inject_target==="head")F.head.appendChild(l);else{var u,c=F.querySelectorAll("body > script");c.length>0?(u=c[0].parentNode)==null||u.insertBefore(l,c[0]):F.body.appendChild(l)}};F!=null&&F.body?a():F==null||F.addEventListener("DOMContentLoaded",a)};R.__PosthogExtensions__=R.__PosthogExtensions__||{},R.__PosthogExtensions__.loadExternalDependency=(t,e,s)=>{if(e!=="remote-config"){var r;if(t.config.strict_script_versioning)r=t.requestRouter.endpointFor("assets","/static/"+t.version+"/"+e+".js");else{var i="/static/"+e+".js?v="+t.version;if(e==="toolbar"){var n=3e5;i=i+"&t="+Math.floor(Date.now()/n)*n}r=t.requestRouter.endpointFor("assets",i)}Xi(t,r,s)}else{var o=t.requestRouter.endpointFor("assets","/array/"+t.config.token+"/config.js");Xi(t,o,s)}},R.__PosthogExtensions__.loadSiteApp=(t,e,s)=>{var r=t.requestRouter.endpointFor("api",e);Xi(t,r,s)};Y.DEBUG=!1,Y.LIB_VERSION="1.415.7",Y.LIB_NAME="web";var Qc="$people_distinct_id",Qs="$device_id",Qi="$device_model",Ls="__alias",Bs="__timers",Ln="$autocapture_disabled_server_side",Bn="$heatmaps_enabled_server_side",Dn="$exception_capture_enabled_server_side",jn="$error_tracking_suppression_rules",Un="$error_tracking_capture_extension_exceptions",Hn="$web_vitals_enabled_server_side",Oo="$dead_clicks_enabled_server_side",Lo="$product_tours_enabled_server_side",Wn="$web_vitals_allowed_metrics",zt="$session_recording_remote_config",eu="$replay_sample_rate",tu="$replay_override_sampling",su="$replay_override_linked_flag",ru="$replay_override_url_trigger",iu="$replay_override_event_trigger",as="$sesid",Bo="$session_is_sampled",Lt="$enabled_feature_flags",Ds="$active_feature_flags",Pr="$early_access_features",zn="$feature_flag_details",js="$feature_flag_payloads",Ar="$feature_flag_request_id",Xr="$minimal_flag_called_events",Qe="$override_feature_flags",Bt="$override_feature_flag_payloads",lt="$stored_person_properties",Dt="$stored_group_properties",qn="$surveys",Qr="$surveys_loaded_at",Vn="$surveys_activated",$r="$surveys_activated_session",Rr="$surveys_activated_timestamps",Us="ph_product_tours",Ut="$flag_call_reported",Hs="$flag_call_reported_session_id",Tr="$feature_flag_errors",qs="$feature_flag_evaluated_at",He="$user_state",Gn="$client_session_props",Kn="$capture_rate_limit",Jn="$initial_campaign_params",Yn="$initial_referrer_info",ei="$initial_person_info",ti="$epp",vr="$posthog_cookieless",nu="$cookieless_mode",ou="$sdk_debug_extensions_init_method",au="$sdk_debug_extensions_init_time_ms",lu="$sdk_debug_recording_script_not_loaded",Do="PostHog loadExternalDependency extension not found.",jt="on_reject",dt="always",Qt="anonymous",$t="identified",Zn="identified_only",si="visibilitychange",ri="beforeunload",is="$pageview",en="$pageleave",tn="$identify",Ga="$groupidentify";function _r(t,e){B(t)&&t.forEach(e)}function Z(t,e){if(!D(t))if(B(t))t.forEach(e);else if(oh(t))t.forEach((r,i)=>e(r,i));else for(var s in t)Ec.call(t,s)&&e(t[s],s)}var ee=function(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;e>r;r++)s[r-1]=arguments[r];for(var i of s)for(var n in i)i[n]!==void 0&&(t[n]=i[n]);return t};function Nr(t){for(var e=Object.keys(t),s=e.length,r=new Array(s);s--;)r[s]=[e[s],t[e[s]]];return r}var Ka=function(t){try{return t()}catch{return}},Yh=function(t){return function(){try{for(var e=arguments.length,s=new Array(e),r=0;e>r;r++)s[r]=arguments[r];return t.apply(this,s)}catch(i){C.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),C.critical(i)}}},jo=function(t){var e={};return Z(t,function(s,r){(W(s)&&s.length>0||he(s))&&(e[r]=s)}),e},Zh=["herokuapp.com","vercel.app","netlify.app"];function Xh(t){var e=t==null?void 0:t.hostname;if(!W(e))return!1;var s=e.split(".").slice(-2).join(".");for(var r of Zh)if(s===r)return!1;return!0}function ie(t,e,s,r){var i=r??{},n=i.capture,o=i.passive;t==null||t.addEventListener(e,s,{capture:n!==void 0&&n,passive:o===void 0||o})}function Xn(t){return t.name==="ph_toolbar_internal"}var cu=t=>{if(F){try{for(var e=t+"=",s=F.cookie.split(";").filter(n=>n.length),r=0;s.length>r;r++){for(var i=s[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(t){return 0>t?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return he(t)&&isFinite(t)&&Math.floor(t)===t});class ii{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,s,r,i){if(!Number.isInteger(e)||!Number.isInteger(s)||!Number.isInteger(r)||!Number.isInteger(i)||0>e||0>s||0>r||0>i||e>0xffffffffffff||s>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var n=new Uint8Array(16);return n[0]=e/Math.pow(2,40),n[1]=e/Math.pow(2,32),n[2]=e/Math.pow(2,24),n[3]=e/Math.pow(2,16),n[4]=e/256,n[5]=e,n[6]=112|s>>>8,n[7]=s,n[8]=128|r>>>24,n[9]=r>>>16,n[10]=r>>>8,n[11]=r,n[12]=i>>>24,n[13]=i>>>16,n[14]=i>>>8,n[15]=i,new ii(n)}toString(){for(var e="",s=0;this.bytes.length>s;s++)e=e+(this.bytes[s]>>>4).toString(16)+(15&this.bytes[s]).toString(16),s!==3&&s!==5&&s!==7&&s!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new ii(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var s=0;16>s;s++){var r=this.bytes[s]-e.bytes[s];if(r!==0)return Math.sign(r)}return 0}}class Qh{generate(){var e=this.generateOrAbort();if(!I(e))return e;this.S=0;var s=this.generateOrAbort();if(I(s))throw new Error("Could not generate UUID after timestamp reset");return s}generateOrAbort(){var e=Date.now();if(e>this.S)this.S=e,this.C();else{if(this.S>=e+1e4)return;this.I++,this.I>4398046511103&&(this.S++,this.C())}return ii.fromFieldsV7(this.S,Math.trunc(this.I/Math.pow(2,30)),this.I&Math.pow(2,30)-1,this.A.nextUint32())}C(){this.I=1024*this.A.nextUint32()+(1023&this.A.nextUint32())}constructor(){this.S=0,this.I=0,this.A=new ep}}var Ja,uu=t=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;t.length>e;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};m&&!I(m.crypto)&&crypto.getRandomValues&&(uu=t=>crypto.getRandomValues(t));class ep{nextUint32(){return this.R.length>this.O||(uu(this.R),this.O=0),this.R[this.O++]}constructor(){this.R=new Uint32Array(8),this.O=1/0}}var ut=()=>tp().toString(),tp=()=>(Ja||(Ja=new Qh)).generate(),Fs="",sp=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,ht={N:()=>!!F,j(t){C.error("cookieStore error: "+t)},P:cu,H(t){var e;try{e=JSON.parse(ht.P(t))||{}}catch{}return e},F(t,e,s,r,i){if(!F)return!1;try{var n="",o="",a=function(c,d){if(d){var h=function(f,g){if(g===void 0&&(g=F),Fs)return Fs;if(!g||["localhost","127.0.0.1"].includes(f))return"";for(var v=f.split("."),_=Math.min(v.length,8),w="dmn_chk_"+ut();!Fs&&_--;){var S=v.slice(_).join("."),k=w+"=1;domain=."+S+";path=/";g.cookie=k+";max-age=3",g.cookie.includes(w)&&(g.cookie=k+";max-age=0",Fs=S)}return Fs}(c);if(!h){var p=(f=>{var g=f.match(sp);return g?g[0]:""})(c);p!==h&&C.info("Warning: cookie subdomain discovery mismatch",p,h),h=p}return h?"; domain=."+h:""}return""}(F.location.hostname,r);if(s){var l=new Date;l.setTime(l.getTime()+864e5*s),n="; expires="+l.toUTCString()}i&&(o="; secure");var u=t+"="+encodeURIComponent(JSON.stringify(e))+n+"; SameSite=Lax; path=/"+a+o;return u.length>3686.4&&C.warn("cookieStore warning: large cookie, len="+u.length),F.cookie=u,!0}catch{return!1}},q(t,e){if(F!=null&&F.cookie)try{ht.F(t,"",-1,e)}catch{return}}},sn=null,Q={N(){if(!$e(sn))return sn;var t=!0;if(I(m))t=!1;else try{var e="__mplssupport__";Q.F(e,"xyz"),Q.P(e)!=='"xyz"'&&(t=!1),Q.q(e)}catch{t=!1}return t||C.error("localStorage unsupported; falling back to cookie store"),sn=t,t},j(t){C.error("localStorage error: "+t)},P(t){try{return m==null?void 0:m.localStorage.getItem(t)}catch(e){Q.j(e)}return null},H(t){try{return JSON.parse(Q.P(t))||{}}catch{}return null},F(t,e){try{return m==null||m.localStorage.setItem(t,JSON.stringify(e)),!0}catch(s){Q.j(s)}return!1},q(t){try{m==null||m.localStorage.removeItem(t)}catch(e){Q.j(e)}}},rp=[Qs,"distinct_id",as,Bo,ti,ei,He],yr={},ip={N:()=>!0,j(t){C.error("memoryStorage error: "+t)},P:t=>yr[t]||null,H:t=>yr[t]||null,F:(t,e)=>(yr[t]=e,!0),q(t){delete yr[t]}},Rt=null,ce={N(){if(!$e(Rt))return Rt;if(Rt=!0,I(m))Rt=!1;else try{var t="__support__";ce.F(t,"xyz"),ce.P(t)!=='"xyz"'&&(Rt=!1),ce.q(t)}catch{Rt=!1}return Rt},j(t){C.error("sessionStorage error: ",t)},P(t){try{return m==null?void 0:m.sessionStorage.getItem(t)}catch(e){ce.j(e)}return null},H(t){try{return JSON.parse(ce.P(t))||null}catch{}return null},F(t,e){try{return m==null||m.sessionStorage.setItem(t,JSON.stringify(e)),!0}catch(s){ce.j(s)}return!1},q(t){try{m==null||m.sessionStorage.removeItem(t)}catch(e){ce.j(e)}}};class np{constructor(e){this._instance=e}get Ne(){return this._instance.config}get consent(){return this.ti()?0:this.ei}isOptedOut(){return this.Ne.cookieless_mode===dt||this.isRejected()||this.consent===-1&&this.Ne.cookieless_mode===jt}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ne.opt_out_capturing_by_default}optInOut(e){this.ii.F(this.ri,e?1:0,this.Ne.cookie_expiration,this.Ne.cross_subdomain_cookie,this.Ne.secure_cookie)}reset(){this.ii.q(this.ri,this.Ne.cross_subdomain_cookie)}get ri(){var e=this._instance.config,s=e.token,r=e.opt_out_capturing_cookie_prefix;return e.consent_persistence_name||(r?r+s:"__ph_opt_in_out_"+s)}get ei(){var e=this.ii.P(this.ri);return Gi(e)?1:L(uh,e)?0:-1}get ii(){var e=this.Ne.opt_out_capturing_persistence_type,s=e==="localStorage"?Q:ht;if(!this.ni||this.ni!==s){this.ni=s;var r=e==="localStorage"?ht:Q;r.P(this.ri)&&(this.ni.P(this.ri)||this.optInOut(Gi(r.P(this.ri))),r.q(this.ri,this.Ne.cross_subdomain_cookie))}return this.ni}ti(){return!!this.Ne.respect_dnt&&[ke==null?void 0:ke.doNotTrack,ke==null?void 0:ke.msDoNotTrack,R.doNotTrack].some(e=>Gi(e))}}function du(t,e){var s,r=t==null||(s=t.config)==null?void 0:s.get_current_url;if(!Se(r))return e;try{var i=r(e);return W(i)&&i?i:e}catch(n){return C.error("Error in get_current_url, falling back to window.location.href",n),e}}var hu="__POSTHOG_TOOLBAR__",op=1,ap=3,lp=11;function Ya(t){return t instanceof Element&&(t.id===hu||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Ct(t){return!!t&&t.nodeType===op}function Me(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function pu(t){return!!t&&t.nodeType===ap}function fu(t){return!!t&&t.nodeType===lp&&Ct(t.host)}var gu=1e3;function Uo(t){return t?Ii(t).split(/\s+/):[]}function Za(t,e){var s=function(r){var i,n=m==null||(i=m.location)==null?void 0:i.href;return I(n)?void 0:du(r,n)}(e);return!!(s&&t&&t.some(r=>s.match(r)))}function ni(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return Uo(e)}function mu(t){return D(t)?null:Ii(t).split(/(\s+)/).filter(e=>Vs(e)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function er(t){var e="";return eo(t)&&!wu(t)&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,function(s){var r;pu(s)&&s.textContent&&(e+=(r=mu(s.textContent))!==null&&r!==void 0?r:"")}),Ii(e)}function rn(t){var e;return I(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null}var Ho=["a","button","form","input","select","textarea","label"];function Qn(t,e){if(I(e))return!0;var s,r=function(n){if(e.some(o=>function(a,l){var u=a.matches||a.matchesSelector||a.msMatchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.oMatchesSelector;try{return!!u&&u.call(a,l)}catch{return!1}}(n,o)))return{v:!0}};for(var i of t)if(s=r(i))return s.v;return!1}function vu(t){var e=t.parentNode;return!(!e||!Ct(e))&&e}var cp=[".ph-no-autocapture","[data-ph-no-autocapture]"],_u=["next","previous","prev",">","<"],up=[..._u,"+","-","−","–"],Xa=(t,e)=>/[a-z0-9]/i.test(e)?t.includes(e):t===e,Qa=[".ph-no-rageclick",".ph-no-capture"],dp=["","text","search","email","password","url","tel","number"];function el(t,e){if(!m||Wo(t))return!1;var s,r,i,n,o;if(Ge(e)?(s=!!e&&Qa,r=void 0,i=!1):(s=(n=e==null?void 0:e.css_selector_ignorelist)!==null&&n!==void 0?n:Qa,r=e==null?void 0:e.content_ignorelist,i=(o=e==null?void 0:e.ignore_text_selection)!==null&&o!==void 0&&o),s===!1||i&&function(l){return!(!l||!Ct(l))&&(!!Me(l,"textarea")||(Me(l,"input")?L(dp,(l.getAttribute("type")||"").toLowerCase()):function(u){if(u.isContentEditable)return!0;var c=u.getAttribute==null?void 0:u.getAttribute("contenteditable");return c==="true"||c===""}(l)))}(t))return!1;var a=yu(t,!1).targetElementList;return!function(l,u){if(l===!1||I(l))return!1;var c;if(l===!0)c=_u;else{if(!B(l))return!1;if(l.length>10)return C.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;c=l.map(d=>d.toLowerCase())}return u.some(d=>{var h=d.safeText,p=d.ariaLabel;return c.some(f=>Xa(h,f)||Xa(p,f))})}(r,a.map(l=>{var u;return{safeText:er(l).toLowerCase(),ariaLabel:((u=l.getAttribute("aria-label"))==null?void 0:u.toLowerCase().trim())||""}}))&&!Qn(a,s)}var Wo=t=>!t||Me(t,"html")||!Ct(t),yu=(t,e)=>{if(!m||Wo(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var s=!1,r=[t],i=t;i.parentNode&&!Me(i,"body");)if(fu(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var n=vu(i);if(!n)break;if(e||Ho.indexOf(n.tagName.toLowerCase())>-1)s=!0;else try{var o=m.getComputedStyle(n);o&&o.getPropertyValue("cursor")==="pointer"&&(s=!0)}catch{}r.push(n),i=n}return{parentIsUsefulElement:s,targetElementList:r}};function eo(t){for(var e=new Set,s=0,r=t;r.parentNode&&!Me(r,"body");r=r.parentNode){if(s++>=gu||e.has(r))return!1;e.add(r);var i=ni(r);if(L(i,"ph-sensitive")||L(i,"ph-no-capture"))return!1}if(L(ni(t),"ph-include"))return!0;var n=t.type||"";if(W(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}var o=t.name||t.id||"";return!W(o)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(o.replace(/[^a-zA-Z0-9]/g,""))}function wu(t){return!!(Me(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||Me(t,"select")||Me(t,"textarea")||t.getAttribute("contenteditable")==="true")}var tl=new RegExp("^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$"),sl=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,hp=[16,15,14,13],pp=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),rl=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),il=/[0-9A-Za-z_]/;function fp(t){for(var e=0,s=!1,r=t.length-1;r>=0;r--){var i=t.charCodeAt(r)-48;s&&(i*=2)>9&&(i-=9),e+=i,s=!s}return e%10==0}function Vs(t,e){if(e===void 0&&(e=!0),D(t))return!1;if(W(t)){t=Ii(t);var s=e?tl.test((t||"").replace(/[- ]/g,"")):function(i){var n;for(sl.lastIndex=0;n=sl.exec(i);){var o=n[2];if(o)for(var a=o.replace(/[- ]/g,""),l=0;a.length>l;l++)for(var u of hp){var c=l+u;if(a.length>=c){var d=a.slice(l,c);if(tl.test(d)&&fp(d))return!0}}}return!1}(t);if(s)return!1;var r=e?pp.test(t):function(i){var n;for(rl.lastIndex=0;n=rl.exec(i);){var o=n[1],a=n[3];if(!(o&&a&&il.test(o)&&il.test(a)))return!0}return!1}(t);if(r)return!1}return!0}function nl(t){var e=er(t);return Vs(e=(e+" "+bu(t)).trim())?e:""}function bu(t){var e="";return t&&t.childNodes&&t.childNodes.length&&Z(t.childNodes,function(s){var r;if(s&&((r=s.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=er(s);e=(e+" "+i).trim(),s.childNodes&&s.childNodes.length&&(e=(e+" "+bu(s)).trim())}catch(n){C.error("[AutoCapture]",n)}}),e}function ol(t){return t.replace(/"|\\"/g,'\\"')}function gp(t){var e=t.attr__class;if(e)return B(e)?e:Uo(e)}var wr=se("[Dead Clicks]"),mp=()=>!0,vp=t=>{var e,s=!((e=t.instance.persistence)==null||!e.get_property(Oo)),r=t.instance.config.capture_dead_clicks;return Ge(r)?r:!!te(r)||s};class al{get lazyLoadedDeadClicksAutocapture(){return this.si}constructor(e,s,r){this.instance=e,this.isEnabled=s,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(e.ok){var s=e.config;"captureDeadClicks"in s&&(this.instance.persistence&&this.instance.persistence.register({[Oo]:s.captureDeadClicks}),this.startIfEnabledOrStop())}}startIfEnabledOrStop(){this.isEnabled(this)?this.ai(()=>{this.oi()}):this.stop()}ai(e){var s,r;(s=R.__PosthogExtensions__)!=null&&s.initDeadClicksAutocapture?e():(r=R.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",i=>{i?wr.error("failed to load script",i):e()})}oi(){var e;if(F){if(!this.si&&(e=R.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var s=te(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};s.__onCapture=this.onCapture,this.onCapture&&(s.capture_dead_swipes=!1),this.si=R.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,s),this.si.start(F),wr.info("starting...")}}else wr.error("`document` not found. Cannot start.")}stop(){this.si&&(this.si.stop(),this.si=void 0,wr.info("stopping..."))}}var nn=se("[SegmentIntegration]"),Eu="posthog-js";function Su(t,e){var s=e===void 0?{}:e,r=s.organization,i=s.projectId,n=s.prefix,o=s.severityAllowList,a=o===void 0?["error"]:o,l=s.sendExceptionsToPostHog,u=l===void 0||l;return c=>{var d,h,p,f,g;if(a!=="*"&&!a.includes(c.level)||!t.__loaded)return c;c.tags||(c.tags={});var v=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());c.tags["PostHog Person URL"]=v,t.sessionRecordingStarted()&&(c.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var _,w=((d=c.exception)==null?void 0:d.values)||[],S=w.map(x=>b({},x,{stacktrace:x.stacktrace?b({},x.stacktrace,{type:"raw",frames:(x.stacktrace.frames||[]).map(P=>b({},P,{platform:"web:javascript"}))}):void 0})),k={$exception_message:((h=w[0])==null?void 0:h.value)||c.message,$exception_type:(p=w[0])==null?void 0:p.type,$exception_level:c.level,$exception_list:S,$sentry_event_id:c.event_id,$sentry_exception:c.exception,$sentry_exception_message:((f=w[0])==null?void 0:f.value)||c.message,$sentry_exception_type:(g=w[0])==null?void 0:g.type,$sentry_tags:c.tags};return r&&i&&(k.$sentry_url=(n||"https://sentry.io/organizations/")+r+"/issues/?project="+i+"&query="+c.event_id),u&&((_=t.exceptions)==null||_.sendExceptionEvent(k)),c}}class _p{constructor(e,s,r,i,n,o){this.name=Eu,this.setupOnce=function(a){a(Su(e,{organization:s,projectId:r,prefix:i,severityAllowList:n,sendExceptionsToPostHog:o==null||o}))}}}class ll{constructor(e){this.li=(s,r,i)=>{i&&(i.noSessionId||i.activityTimeout||i.sessionPastMaximumLength||i.crossTabAdoption)&&(C.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:s,changeReason:i}),this.ui=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.hi()}hi(){var e;this.di=(e=this._instance.sessionManager)==null?void 0:e.onSessionId(this.li)}destroy(){var e;(e=this.di)==null||e.call(this),this.di=void 0}doPageView(e,s){var r,i=this.vi(e,s);return this.ui={pathname:(r=m==null?void 0:m.location.pathname)!==null&&r!==void 0?r:"",pageViewId:s,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var s;return this.vi(e,(s=this.ui)==null?void 0:s.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.ui)==null?void 0:e.pageViewId}}vi(e,s){var r=this.ui;if(!r)return{$pageview_id:s};var i={$pageview_id:s,$prev_pageview_id:r.pageViewId},n=this._instance.scrollManager.getContext();if(n&&!this._instance.config.disable_scroll_properties){var o=n.maxScrollHeight,a=n.lastScrollY,l=n.maxScrollY,u=n.maxContentHeight,c=n.lastContentY,d=n.maxContentY;if(!(I(o)||I(a)||I(l)||I(u)||I(c)||I(d))){o=Math.ceil(o),a=Math.ceil(a),l=Math.ceil(l),u=Math.ceil(u),c=Math.ceil(c),d=Math.ceil(d);var h=o>1?st(a/o,0,1,C):1,p=o>1?st(l/o,0,1,C):1,f=u>1?st(c/u,0,1,C):1,g=u>1?st(d/u,0,1,C):1;i=ee(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:p,$prev_pageview_last_content:c,$prev_pageview_last_content_percentage:f,$prev_pageview_max_content:d,$prev_pageview_max_content_percentage:g})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),i}}var on=["flags","surveys"],yp={[Qc]:{exposure:"hidden"},[Ls]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Bs]:{exposure:"hidden"},[Ln]:{exposure:"event"},[Bn]:{exposure:"hidden"},[Dn]:{exposure:"event"},[jn]:{exposure:"hidden"},[Un]:{exposure:"event"},[Hn]:{exposure:"event"},[Oo]:{exposure:"event"},[Lo]:{exposure:"hidden"},[Wn]:{exposure:"event"},[zt]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[as]:{exposure:"hidden"},[Bo]:{exposure:"event"},[eu]:{exposure:"event",shouldSkipFromEventProperties:t=>$e(t)},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},$sess_rec_flush_size:{exposure:"hidden"},[Lt]:{exposure:"hidden",storageGroup:"flags"},[Ds]:{exposure:"hidden",storageGroup:"flags"},[Pr]:{exposure:"hidden"},[zn]:{exposure:"hidden",storageGroup:"flags"},[js]:{exposure:"hidden",storageGroup:"flags"},[Ar]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Xr]:{exposure:"hidden",storageGroup:"flags"},[Qe]:{exposure:"hidden"},[Bt]:{exposure:"hidden"},[lt]:{exposure:"hidden"},[Dt]:{exposure:"hidden"},[qn]:{exposure:"hidden",storageGroup:"surveys"},[Qr]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[Vn]:{exposure:"event"},[$r]:{exposure:"hidden"},[Rr]:{exposure:"hidden"},[Us]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$product_tours_activated_session:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[Ut]:{exposure:"hidden"},[Hs]:{exposure:"hidden"},[Tr]:{exposure:"hidden"},[qs]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[He]:{exposure:"hidden"},[Gn]:{exposure:"hidden"},[Kn]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},[Yn]:{exposure:"hidden"},[ei]:{exposure:"hidden"},[ti]:{exposure:"hidden"},[tu]:{exposure:"event"},[su]:{exposure:"event"},[ru]:{exposure:"event"},[iu]:{exposure:"event"},[ou]:{exposure:"event"},[au]:{exposure:"event"},[lu]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},wp=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Tt=t=>{var e=yp[t];if(e)return e;for(var s of wp){var r=s[1];if(t.indexOf(s[0])===0)return r}},ls=(t,e)=>{try{return JSON.stringify(t,(s,r)=>typeof r=="bigint"?r.toString():r,e)}catch{return wc(t)}},oi=t=>{var e=F==null?void 0:F.createElement("a");return I(e)?null:(e.href=t,e)},ms=function(t,e){for(var s,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;r.length>i;i++){var n=r[i].split("=");if(n[0]===e){s=n;break}}if(!B(s)||2>s.length)return"";var o=s[1];try{o=decodeURIComponent(o)}catch{C.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},tr=function(t,e,s){if(!t||!e||!e.length)return t;for(var r=t.split("#"),i=r[1],n=(r[0]||"").split("?"),o=n[1],a=n[0],l=(o||"").split("&"),u=[],c=0;l.length>c;c++){var d=l[c].split("=");B(d)&&(e.includes(d[0])?u.push(d[0]+"="+s):u.push(l[c]))}var h=a;return o!=null&&(h+="?"+u.join("&")),i!=null&&(h+="#"+i),h},ai=function(t,e){var s=t.match(new RegExp(e+"=([^&]*)"));return s?s[1]:null},xu=(t,e)=>t>=e&&vc(),ku=(t,e,s,r)=>{if(t===0){if(vc()){var i=e+1;return i===s&&r(),i}return e}return 0},br="https?://(.*)",vs=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],bp=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...vs],sr="",Ep=["li_fat_id"];function Iu(t,e,s){if(!F)return{};var r,i=e?[...vs,...s||[]]:[],n=Cu(tr(F.URL,i,sr),t),o=(r={},Z(Ep,function(a){var l=cu(a);r[a]=l||null}),r);return ee(o,n)}function Cu(t,e){var s=bp.concat(e||[]),r={};return Z(s,function(i){var n=ms(t,i);r[i]=n||null}),r}function Fu(t){var e=function(n){return n?n.search(br+"google.([^/?]*)")===0?"google":n.search(br+"bing.com")===0?"bing":n.search(br+"yahoo.com")===0?"yahoo":n.search(br+"duckduckgo.com")===0?"duckduckgo":null:null}(t),s=e!="yahoo"?"q":"p",r={};if(!$e(e)){r.$search_engine=e;var i=F?ms(F.referrer,s):"";i.length&&(r.ph_keyword=i)}return r}function cl(){return navigator.language||navigator.userLanguage}var li="$direct";function Pu(){return(F==null?void 0:F.referrer)||li}function Au(t,e,s){s===void 0&&(s=!1);var r=t?[...vs,...e||[]]:[],i=s?It(re==null?void 0:re.href):re==null?void 0:re.href,n=i==null?void 0:i.substring(0,1e3);return{r:Pu().substring(0,1e3),u:n?tr(n,r,sr):void 0}}function $u(t,e){var s;e===void 0&&(e=!1);var r=t.r,i=t.u,n=e?It(i):i,o={$referrer:r,$referring_domain:r==null?void 0:r==li?li:(s=oi(r))==null?void 0:s.host};if(n){o.$current_url=n;var a=oi(n);o.$host=a==null?void 0:a.host,o.$pathname=a==null?void 0:a.pathname;var l=Cu(n);ee(o,l)}if(r){var u=Fu(r);ee(o,u)}return o}function Ru(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Sp(){try{return new Date().getTimezoneOffset()}catch{return}}var xp={flags:qs,surveys:Qr},kp=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],es="main";class an{constructor(e,s,r){if(r===void 0&&(r=!0),this.ci={},this.fi=!1,this.pi=!1,this.Ne=e,this.gi=r,this.props={},this.mi=void 0,this.yi=(n=>{var o="";return n.token&&(o=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+o+"_posthog"})(e),this.ii=this.bi(e),this.pi=this.wi(e),this.load(),e.debug&&C.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,s),this.save(),m){var i=()=>this.flush();ie(m,"beforeunload",i,{capture:!1}),ie(m,"pagehide",i,{capture:!1})}}ki(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return he(s)&&s>0?s:0}isDisabled(){return!!this.xi}bi(e){kp.indexOf(e.persistence.toLowerCase())===-1&&(C.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var s,r=function(o,a){o===void 0&&(o=[]),a===void 0&&(a=!1);var l=[...rp,...o];return b({},Q,{H(u){try{var c={};try{c=ht.H(u)||{}}catch{}var d,h=JSON.parse(Q.P(u)||"{}");if(a){var p={};for(var f in c){var g=c[f];$e(g)||g===""||(p[f]=g)}d=ee(h,p)}else d=ee(c,h);return Q.F(u,d),d}catch{}return null},F(u,c,d,h,p,f){var g=Q.F(u,c,void 0,void 0,f);try{var v={};l.forEach(_=>{c[_]&&(v[_]=c[_])}),Object.keys(v).length&&ht.F(u,v,d,h,p,f)}catch(_){Q.j(_)}return g},q(u,c){try{m==null||m.localStorage.removeItem(u),ht.q(u,c)}catch(d){Q.j(d)}}})}(e.cookie_persisted_properties||[],e.__preview_cookie_wins_on_conflict||!1),i=!1,n=e.persistence.toLowerCase();return n==="localstorage"&&Q.N()?(s=Q,i=!0):n==="localstorage+cookie"&&r.N()?(s=r,i=!0):n==="sessionstorage"&&ce.N()?s=ce:n==="memory"?s=ip:n==="cookie"?s=ht:r.N()?(s=r,i=!0):s=ht,this.fi=i,s}Si(e){return this.yi+"__"+e}wi(e){return this.fi&&!!e.split_storage}properties(){var e={};return Z(this.props,(s,r)=>{var i=Tt(r);if(!i||i.exposure==="event"){if(i!=null&&i.shouldSkipFromEventProperties!=null&&i.shouldSkipFromEventProperties(s))return;e[r]=s}}),e}load(){if(!this.xi){var e=this.ii.H(this.yi);e&&(this.props=ee({},e)),this.pi&&this.Ci()}}Ci(){for(var e of on){var s=Q.H(this.Si(e));if(s&&!gt(s)){var r=this.Mi(e);r.persisted=!0,this.Ti(e)||(r.fingerprint=this.Ei(s,e)),this.Ii(e,s)||ee(this.props,s)}}}Ti(e){return Object.keys(this.props).some(s=>{var r;return((r=Tt(s))==null?void 0:r.storageGroup)===e})}Ii(e,s){var r=xp[e];if(!r)return!1;var i=s[r],n=this.props[r];return he(i)&&he(n)&&n>i}refreshKey(e){var s;if(!this.xi){var r=this.pi?(s=Tt(e))==null?void 0:s.storageGroup:void 0,i=r?Q.H(this.Si(r)):this.ii.H(this.yi);if(i&&e in i)this.Pi(e,i[e]);else{if(r){var n=this.ii.H(this.yi);if(n&&e in n)return void this.Pi(e,n[e])}this.Ri(e)}}}save(){if(!this.xi){var e=this.ki();e>0?I(this.Ai)&&(this.Ai=setTimeout(()=>{this.Ai=void 0,this.Fi()},e)):this.Fi()}}flush(){I(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0,this.Fi())}Fi(){this.xi||(this.pi?this.Li():this.Oi(this.ii,this.yi,this.props,es))}Li(){var e=this.Di(),s=e.main,r=e.groups;for(var i of(this.Oi(this.ii,this.yi,s,es),on)){var n,o=r[i];(!gt(o)||(n=this.ci[i])!=null&&n.persisted)&&this.Oi(Q,this.Si(i),o,i)}}Di(){var e={},s={flags:{},surveys:{}};return Z(this.props,(r,i)=>{var n,o=(n=Tt(i))==null?void 0:n.storageGroup;o?s[o][i]=r:e[i]=r}),{main:e,groups:s}}Ei(e,s){if(s===es)return JSON.stringify(e)+"|"+this.$i+"|"+this.Ni+"|"+this.qi;var r={};return Z(e,(i,n)=>{var o;r[n]=(o=Tt(n))!=null&&o.volatile?"__volatile__":i}),JSON.stringify(r)}Oi(e,s,r,i){var n=this.Mi(i);if(i===es||n.dirty||I(n.fingerprint)){var o;try{if((o=this.Ei(r,i))===n.fingerprint)return void(n.dirty=!1)}catch{o=void 0}e.F(s,r,this.$i,this.Ni,this.qi,this.Ne.debug)?(n.dirty=!1,i!==es&&(n.persisted=!0),I(o)||(n.fingerprint=o)):this.Ne.debug&&C.warn('failed to persist storage entry "'+s+'"; will retry on next save')}}remove(e){var s=(e===void 0?{}:e).keepGroupEntries,r=s!==void 0&&s;if(I(this.Ai)||(clearTimeout(this.Ai),this.Ai=void 0),this.ii.q(this.yi,!1),this.ii.q(this.yi,!0),!r&&this.gi)for(var i of on)Q.q(this.Si(i));r?delete this.ci[es]:this.ci={}}clear(){this.remove(),this.props={}}register_once(e,s,r){if(te(e)){I(s)&&(s="None"),this.$i=I(r)?this.ji:r;var i=!1;if(Z(e,(n,o)=>{this.props.hasOwnProperty(o)&&this.props[o]!==s||(this.Pi(o,n),i=!0)}),i)return this.save(),!0}return!1}register(e,s){if(te(e)){this.$i=I(s)?this.ji:s;var r=!1;if(Z(e,(i,n)=>{e.hasOwnProperty(n)&&(this.props[n]!==i||te(i)||B(i))&&(this.Pi(n,i),r=!0)}),r)return this.save(),!0}return!1}unregister(e){var s=typeof e=="string"?[e]:e,r=!1;for(var i of s)i in this.props&&(this.Ri(i),r=!0);r&&this.save()}update_campaign_params(){var e=F==null?void 0:F.URL;if(e!==this.mi){var s=Iu(this.Ne.custom_campaign_params,this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties);gt(jo(s))||this.register(s),this.mi=e}}update_search_keyword(){var e;this.register((e=F==null?void 0:F.referrer)?Fu(e):{})}update_referrer_info(){var e;this.register_once({$referrer:Pu(),$referring_domain:F!=null&&F.referrer&&((e=oi(F.referrer))==null?void 0:e.host)||li},void 0)}set_initial_person_info(){this.props[Jn]||this.props[Yn]||this.register_once({[ei]:Au(this.Ne.mask_personal_data_properties,this.Ne.custom_personal_data_properties,this.Ne.disable_capture_url_hashes)},void 0)}get_initial_props(){var e={};Z([Yn,Jn],i=>{var n=this.props[i];n&&Z(n,function(o,a){e["$initial_"+An(a)]=o})});var s=this.props[ei];if(s){var r=function(i,n){n===void 0&&(n=!1);var o=$u(i,n),a={};return Z(o,function(l,u){a["$initial_"+An(u)]=l}),a}(s,this.Ne.disable_capture_url_hashes);ee(e,r)}return e}safe_merge(e){return Z(this.props,function(s,r){r in e||(e[r]=s)}),e}update_config(e,s,r){this.ji=this.$i=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie);var i=e.persistence!==s.persistence||!((l,u)=>{if(l.length!==u.length)return!1;var c=[...l].sort(),d=[...u].sort();return c.every((h,p)=>h===d[p])})(e.cookie_persisted_properties||[],s.cookie_persisted_properties||[]),n=i?this.bi(e):this.ii,o=this.wi(e);if(i||o!==this.pi){var a=this.props;this.clear(),this.ii=n,this.pi=o,this.props=a,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Ni&&(this.Ni=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.qi&&(this.qi=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,s){var r=this.props[Bs]||{};r[e]=s,this.Pi(Bs,r),this.save()}remove_event_timer(e){var s=this.props[Bs]||{},r=s[e];return I(r)||(delete s[e],this.Pi(Bs,s),this.save()),r}get_property(e){return this.props[e]}set_property(e,s){this.Pi(e,s),this.save()}Pi(e,s){var r;this.props[e]=s,(r=Tt(e))!=null&&r.volatile||this.Bi(e)}Ri(e){delete this.props[e],this.Bi(e)}Bi(e){var s,r=(s=Tt(e))==null?void 0:s.storageGroup;r&&(this.Mi(r).dirty=!0)}Mi(e){return this.ci[e]||(this.ci[e]={})}}function Er(t){var e=!0;return{dispose(){if(e){e=!1;var s=t();s&&Se(s.then)&&s.then(void 0,()=>{})}}}}var xe={GZipJS:"gzip-js",Base64:"base64"},Ps={Activation:"events",Cancellation:"cancelEvents"},ln={Popover:"popover",API:"api",Widget:"widget"},pt={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},cn={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},to={Popover:"popover",Inline:"inline"},Ip={SHOWN:"product tour shown"},ul={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},dl=se("[RateLimiter]");class Cp{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=s=>{var r=s.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(i=>{dl.info((i||"events")+" is quota limited."),this.serverLimits[i]=new Date().getTime()+6e4})}catch(i){return void dl.warn('could not rate limit - continuing. Error: "'+(i==null?void 0:i.message)+'"',{text:r})}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)==null?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)==null?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e){var s,r,i;e===void 0&&(e=!1);var n=this.captureEventsBurstLimit,o=this.captureEventsPerSecond,a=new Date().getTime(),l=(s=(r=this.instance.persistence)==null?void 0:r.get_property(Kn))!==null&&s!==void 0?s:{tokens:n,last:a};l.tokens+=(a-l.last)/1e3*o,l.last=a,l.tokens>n&&(l.tokens=n);var u=1>l.tokens;if(u||e||(l.tokens=Math.max(0,l.tokens-1)),u&&!e){var c=(he(l.dropped)?l.dropped:0)+1;l.dropped=c,!this.lastEventRateLimited&&this.Hi(c)&&(l.dropped=0)}return this.lastEventRateLimited=u,(i=this.instance.persistence)==null||i.set_property(Kn,l),{isRateLimited:u,remainingTokens:l.tokens}}Ui(e){var s=this.instance.config.property_denylist;return!B(s)||!s.includes(e)}zi(){var e;if(this.Ui("$current_url")&&this.Ui("$pathname")&&re!=null&&re.pathname)return""+((e=re.origin)!==null&&e!==void 0?e:"")+re.pathname}Hi(e){var s,r,i=this.captureEventsBurstLimit,n=this.captureEventsPerSecond,o=this.zi(),a=this.Ui("$session_id")?(s=(r=this.instance).get_session_id)==null?void 0:s.call(r):void 0,l=[e+" event(s) dropped since the last warning",o?"triggered on "+o:void 0,a?"session "+a:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited: "+l+". Config is set to "+n+" events per second and "+i+" events burst limit."},{skip_client_rate_limiting:!0})}isServerRateLimited(e){var s=this.serverLimits[e||"events"]||!1;return s!==!1&&new Date().getTime()e(this.remoteConfig)):e()}Vi(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:e})}load(){try{if(this.remoteConfig)return St.info("Using preloaded remote config",this.remoteConfig),this.Zi(this.remoteConfig),void this.Gi();if(this._instance.Qi())return void St.warn("Remote config is disabled. Falling back to local config.");this.Wi(e=>{if(!e)return St.info("No config found after loading remote JS config. Falling back to JSON."),void this.Vi(s=>{this.Zi(s.json,s),this.Gi()});this.Zi(e),this.Gi()})}catch(e){St.error("Error loading remote config",e),this.Zi()}}stop(){this.Ki&&(clearInterval(this.Ki),this.Ki=void 0)}refresh(){!this._instance.Qi()&&F&&F.visibilityState!=="hidden"&&this._instance.reloadFeatureFlags()}Gi(){var e;if(!this.Ki){var s=(e=this._instance.config.remote_config_refresh_interval_ms)!==null&&e!==void 0?e:3e5;s!==0&&(this.Ki=setInterval(()=>{this.refresh()},s))}}Zi(e,s){!e&&s&&(s.statusCode===0?s.error||St.warn("Failed to fetch remote config from PostHog."):St.error("Failed to fetch remote config from PostHog."));try{this._instance.Zi(e?{ok:!0,config:e}:{ok:!1})}catch(i){St.error("Error applying remote config",i)}if((e==null?void 0:e.hasFeatureFlags)!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)==null||r.ensureFlagsLoaded()}catch(i){St.error("Error loading feature flags",i)}}}var qe=Uint8Array,Ae=Uint16Array,_s=Uint32Array,zo=new qe([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),qo=new qe([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),hl=new qe([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Nu=function(t,e){for(var s=new Ae(31),r=0;31>r;++r)s[r]=e+=1<r;++r)for(var n=s[r];s[r+1]>n;++n)i[n]=n-s[r]<<5|r;return[s,i]},Mu=Nu(zo,2),so=Mu[1];Mu[0][28]=258,so[258]=28;for(var pl=Nu(qo,0)[1],Ou=new Ae(32768),ne=0;32768>ne;++ne){var ts=(43690&ne)>>>1|(21845&ne)<<1;Ou[ne]=((65280&(ts=(61680&(ts=(52428&ts)>>>2|(13107&ts)<<2))>>>4|(3855&ts)<<4))>>>8|(255&ts)<<8)>>>1}var Gs=function(t,e,s){for(var r=t.length,i=0,n=new Ae(e);r>i;++i)++n[t[i]-1];var o,a=new Ae(e);for(i=0;e>i;++i)a[i]=a[i-1]+n[i-1]<<1;for(o=new Ae(r),i=0;r>i;++i)o[i]=Ou[a[t[i]-1]++]>>>15-t[i];return o},Vt=new qe(288);for(ne=0;144>ne;++ne)Vt[ne]=8;for(ne=144;256>ne;++ne)Vt[ne]=9;for(ne=256;280>ne;++ne)Vt[ne]=7;for(ne=280;288>ne;++ne)Vt[ne]=8;var ci=new qe(32);for(ne=0;32>ne;++ne)ci[ne]=5;var Fp=Gs(Vt,9),Pp=Gs(ci,5),Lu=function(t){return(t/8>>0)+(7&t&&1)},Bu=function(t,e,s){(s==null||s>t.length)&&(s=t.length);var r=new(t instanceof Ae?Ae:t instanceof _s?_s:qe)(s-e);return r.set(t.subarray(e,s)),r},nt=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8},As=function(t,e,s){var r=e/8>>0;t[r]|=s<<=7&e,t[r+1]|=s>>>8,t[r+2]|=s>>>16},un=function(t,e){for(var s=[],r=0;t.length>r;++r)t[r]&&s.push({s:r,f:t[r]});var i=s.length,n=s.slice();if(!i)return[new qe(0),0];if(i==1){var o=new qe(s[0].s+1);return o[s[0].s]=1,[o,1]}s.sort(function(x,P){return x.f-P.f}),s.push({s:-1,f:25001});var a=s[0],l=s[1],u=0,c=1,d=2;for(s[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=s[s[d].f>s[u].f?u++:d++],l=s[u!=c&&s[d].f>s[u].f?u++:d++],s[c++]={s:-1,f:a.f+l.f,l:a,r:l};var h=n[0].s;for(r=1;i>r;++r)n[r].s>h&&(h=n[r].s);var p=new Ae(h+1),f=ro(s[c-1],p,0);if(f>e){r=0;var g=0,v=f-e,_=1<r;++r){var w=n[r].s;if(e>=p[w])break;g+=_-(1<>>=v;g>0;){var S=n[r].s;e>p[S]?g-=1<=0&&g;--r){var k=n[r].s;p[k]==e&&(--p[k],++g)}f=e}return[new qe(p),f]},ro=function(t,e,s){return t.s==-1?Math.max(ro(t.l,e,s+1),ro(t.r,e,s+1)):e[t.s]=s},fl=function(t){for(var e=t.length;e&&!t[--e];);for(var s=new Ae(++e),r=0,i=t[0],n=1,o=function(l){s[r++]=l},a=1;e>=a;++a)if(t[a]==i&&a!=e)++n;else{if(!i&&n>2){for(;n>138;n-=138)o(32754);n>2&&(o(n>10?n-11<<5|28690:n-3<<5|12305),n=0)}else if(n>3){for(o(i),--n;n>6;n-=6)o(8304);n>2&&(o(n-3<<5|8208),n=0)}for(;n--;)o(i);n=1,i=t[a]}return[s.subarray(0,r),e]},$s=function(t,e){for(var s=0,r=0;e.length>r;++r)s+=t[r]*e[r];return s},io=function(t,e,s){var r=s.length,i=Lu(e+2);t[i]=255&r,t[i+1]=r>>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var n=0;r>n;++n)t[i+n+4]=s[n];return 8*(i+4+r)},gl=function(t,e,s,r,i,n,o,a,l,u,c){nt(e,c++,s),++i[256];for(var d=un(i,15),h=d[0],p=d[1],f=un(n,15),g=f[0],v=f[1],_=fl(h),w=_[0],S=_[1],k=fl(g),x=k[0],P=k[1],M=new Ae(19),E=0;w.length>E;++E)M[31&w[E]]++;for(E=0;x.length>E;++E)M[31&x[E]]++;for(var A=un(M,7),$=A[0],N=A[1],T=19;T>4&&!$[hl[T-1]];--T);var O,J,z,H,oe=u+5<<3,pe=$s(i,Vt)+$s(n,ci)+o,Ie=$s(i,h)+$s(n,g)+o+14+3*T+$s(M,$)+(2*M[16]+3*M[17]+7*M[18]);if(pe>=oe&&Ie>=oe)return io(e,c,t.subarray(l,l+u));if(nt(e,c,1+(pe>Ie)),c+=2,pe>Ie){O=Gs(h,p),J=h,z=Gs(g,v),H=g;var _e=Gs($,N);for(nt(e,c,S-257),nt(e,c+5,P-1),nt(e,c+10,T-4),c+=14,E=0;T>E;++E)nt(e,c+3*E,$[hl[E]]);c+=3*T;for(var Ce=[w,x],Re=0;2>Re;++Re){var ae=Ce[Re];for(E=0;ae.length>E;++E)nt(e,c,_e[me=31&ae[E]]),c+=$[me],me>15&&(nt(e,c,ae[E]>>>5&127),c+=ae[E]>>>12)}}else O=Fp,J=Vt,z=Pp,H=ci;for(E=0;a>E;++E)if(r[E]>255){var me;As(e,c,O[257+(me=r[E]>>>18&31)]),c+=J[me+257],me>7&&(nt(e,c,r[E]>>>23&31),c+=zo[me]);var ge=31&r[E];As(e,c,z[ge]),c+=H[ge],ge>3&&(As(e,c,r[E]>>>5&8191),c+=qo[ge])}else As(e,c,O[r[E]]),c+=J[r[E]];return As(e,c,O[256]),c+J[256]},Ap=new _s([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$p=function(){for(var t=new _s(256),e=0;256>e;++e){for(var s=e,r=9;--r;)s=(1&s&&3988292384)^s>>>1;t[e]=s}return t}(),dn=function(t,e,s){for(;s;++e)t[e]=s,s>>>=8};function Rp(t,e){e===void 0&&(e={});var s=function(){var d=4294967295;return{p(h){for(var p=d,f=0;h.length>f;++f)p=$p[255&p^h[f]]^p>>>8;d=p},d(){return 4294967295^d}}}(),r=t.length;s.p(t);var i,n,o,a,l,u=(a=10+((i=e).filename&&i.filename.length+1||0),l=8,function(d,h,p,f,g,v){var _=d.length,w=new qe(f+_+5*(1+Math.floor(_/7e3))+g),S=w.subarray(f,w.length-g),k=0;if(!h||8>_)for(var x=0;_>=x;x+=65535){var P=x+65535;_>P?k=io(S,k,d.subarray(x,P)):(S[x]=!0,k=io(S,k,d.subarray(x,_)))}else{for(var M=Ap[h-1],E=M>>>13,A=8191&M,$=(1<x;++x){var me=z(x),ge=32767&x,Je=T[me];if(N[ge]=Je,T[me]=ge,x>=Re){var At=_-x;if((Ie>7e3||Ce>24576)&&At>423){k=gl(d,S,0,H,oe,pe,_e,Ce,ae,x-ae,k),Ce=Ie=_e=0,ae=x;for(var de=0;286>de;++de)oe[de]=0;for(de=0;30>de;++de)pe[de]=0}var Ve=2,Et=0,xs=A,De=ge-Je&32767;if(At>2&&me==z(x-De))for(var Fe=Math.min(E,At)-1,hr=Math.min(32767,x),pr=Math.min(258,At);hr>=De&&--xs&&ge!=Je;){if(d[x+Ve]==d[x+Ve-De]){for(var je=0;pr>je&&d[x+je]==d[x+je-De];++je);if(je>Ve){if(Ve=je,Et=De,je>Fe)break;var fr=Math.min(De,je-2),Zt=0;for(de=0;fr>de;++de){var Xt=x-De+de+32768&32767,ks=Xt-N[Xt]+32768&32767;ks>Zt&&(Zt=ks,Je=Xt)}}}De+=(ge=Je)-(Je=N[ge])+32768&32767}if(Et){H[Ce++]=268435456|so[Ve]<<18|pl[Et];var Ca=31&so[Ve],Fa=31&pl[Et];_e+=zo[Ca]+qo[Fa],++oe[257+Ca],++pe[Fa],Re=x+Ve,++Ie}else H[Ce++]=d[x],++oe[d[x]]}}k=gl(d,S,!0,H,oe,pe,_e,Ce,ae,x-ae,k)}return Bu(w,0,f+Lu(k)+g)}(n=t,(o=e).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+o.mem,a,l)),c=u.length;return function(d,h){var p=h.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>h.level?4:h.level==9?2:0,d[9]=3,h.mtime!=0&&dn(d,4,Math.floor(new Date(h.mtime||Date.now())/1e3)),p){d[3]=8;for(var f=0;p.length>=f;++f)d[f+10]=p.charCodeAt(f)}}(u,e),dn(u,c-8,s.d()),dn(u,c-4,r),u}var Tp=!!Cn||!!Po,Du="text/plain",Mr=!1,ju=(t,e)=>{var s=t.split("#"),r=s[1],i=s[0].split("?"),n=i[0],o=i[1];if(!o)return t;var a=o.split("&").filter(l=>l.split("=")[0]!==e).join("&");return n+(a?"?"+a:"")+(r?"#"+r:"")},Fi=function(t,e,s){var r;s===void 0&&(s=!0);var i=t.split("?"),n=i[0],o=i[1],a=b({},e),l=(r=o==null?void 0:o.split("&").map(c=>{var d,h=c.split("="),p=h[0],f=s&&(d=a[p])!==null&&d!==void 0?d:h[1];return delete a[p],p+"="+f}))!==null&&r!==void 0?r:[],u=function(c,d){var h,p;d===void 0&&(d="&");var f=[];return Z(c,function(g,v){I(g)||I(v)||v==="undefined"||(h=encodeURIComponent((_=>_ instanceof File)(g)?g.name:g.toString()),p=encodeURIComponent(v),f[f.length]=p+"="+h)}),f.join(d)}(a);return u&&l.push(u),l.length>0?n+"?"+l.join("&"):n},hn=t=>{if(t.Ji)return t.Ji;var e=t.data,s=t.compression;if(e){if(s===xe.GZipJS){var r=Rp(function(a,l){var u=a.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(a);for(var c=new qe(a.length+(a.length>>>1)),d=0,h=function(v){c[d++]=v},p=0;u>p;++p){if(d+5>c.length){var f=new qe(d+8+(u-p<<1));f.set(c),c=f}var g=a.charCodeAt(p);128>g?h(g):2048>g?(h(192|g>>>6),h(128|63&g)):g>55295&&57344>g?(h(240|(g=65536+(1047552&g)|1023&a.charCodeAt(++p))>>>18),h(128|g>>>12&63),h(128|g>>>6&63),h(128|63&g)):(h(224|g>>>12),h(128|g>>>6&63),h(128|63&g))}return Bu(c,0,d)}(ls(e)),{mtime:0});return{contentType:Du,body:r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength),estimatedSize:r.byteLength}}if(s===xe.Base64){var i=function(a){return a&&btoa(encodeURIComponent(a).replace(/%([0-9A-F]{2})/g,(l,u)=>String.fromCharCode(parseInt(u,16))))}(ls(e)),n=(a=>"data="+encodeURIComponent(typeof a=="string"?a:ls(a)))(i);return{contentType:"application/x-www-form-urlencoded",body:n,estimatedSize:new Blob([n]).size}}var o=ls(e);return{contentType:"application/json",body:o,estimatedSize:new Blob([o]).size}}},Uu=t=>{var e,s,r=()=>t.transport==="sendBeacon"?{url:Fi(t.url,{compression:xe.Base64}),encodedBody:hn(b({},t,{compression:xe.Base64,Ji:void 0}))}:{url:ju(t.url,"compression"),encodedBody:hn(b({},t,{compression:void 0,Ji:void 0}))};try{e=hn(t)}catch(i){if(Ma(t.compression,ms(t.url,"compression")))return C.error("Failed to gzip request body, sending uncompressed payload",i),r();throw i}return e&&Ma(t.compression,ms(t.url,"compression"))&&!((s=e.body)instanceof ArrayBuffer?Fn(new Uint8Array(s)):ArrayBuffer.isView(s)&&Fn(new Uint8Array(s.buffer,s.byteOffset,s.byteLength)))?(Mr=!0,r()):{url:t.url,encodedBody:e}},Hu=t=>{try{return Uu(t)}catch(e){return C.error(e),void(t.callback==null||t.callback({statusCode:0,error:e}))}},Np=function(){var t=X(function*(e){var s=ls(e.data),r=yield function(n,o,a){return Pn.apply(this,arguments)}(s,Y.DEBUG,{rethrow:!0});if(!r)return e;var i=yield r.arrayBuffer();return b({},e,{Ji:{contentType:Du,body:i,estimatedSize:i.byteLength}})});return function(e){return t.apply(this,arguments)}}(),Mp=/Failed to fetch|NetworkError|Load failed/i,Wu=t=>(t==null?void 0:t.name)==="TypeError"&&Mp.test((t==null?void 0:t.message)||""),zu=t=>{var e=Hu(t);if(e){var s=e.url,r=e.encodedBody,i=r??{},n=i.contentType,o=i.body,a=i.estimatedSize,l=new Headers;Z(t.headers,function(f,g){l.append(g,f)}),n&&l.append("Content-Type",n);var u=null,c=!1;if(Pa){var d=new Pa;u={signal:d.signal,timeout:setTimeout(()=>{var f,g;c=!0,d.abort((f=t.timeout,(g=new Error("PostHog request timed out"+(f?" after "+f+"ms":""))).name="AbortError",g))},t.timeout)}}var h=f=>{c&&(f==null?void 0:f.name)==="AbortError"||Wu(f)?C.warn(f):C.error(f),t.callback==null||t.callback({statusCode:0,error:f})};try{var p;Po(s,b({method:(t==null?void 0:t.method)||"GET",headers:l,keepalive:t.method==="POST"&&!t.Yi&&52428.8>(a||0),body:o,signal:(p=u)==null?void 0:p.signal},t.fetchOptions)).then(f=>f.text().then(g=>{var v={statusCode:f.status,text:g};if(f.status===200)try{v.json=JSON.parse(g)}catch(_){C.error(_)}t.callback==null||t.callback(v)})).catch(h).finally(()=>u?clearTimeout(u.timeout):null)}catch(f){u&&clearTimeout(u.timeout),h(f)}}},no=t=>{try{var e,s=Uu(t),r=s.url,i=s.encodedBody,n=i??{},o=n.body,a=n.estimatedSize;if(!o)return;var l=o instanceof Blob?o:new Blob([o],{type:n.contentType});if(ke.sendBeacon(r,l))return;var u=B(t.data)?t.data:(e=t.data)==null?void 0:e.batch;if(B(u)&&u.length>1&&(a??0)>16384){var c=Math.ceil(u.length/2),d=h=>B(t.data)?h:b({},t.data,{batch:h});return no(b({},t,{data:d(u.slice(0,c))})),void no(b({},t,{data:d(u.slice(c))}))}C.warn("Beacon of ~"+(a??0)+" bytes was rejected by the browser, falling back to fetch"),zu(b({},t,{Yi:!0}))}catch(h){C.warn("Beacon send failed",h)}},ml=(t,e,s,r)=>{var i=r==="query"?e==="POST"?"sent_at":"_":void 0;return Fi(s===xe.GZipJS?ju(t,"compression"):t,b({},i?{[i]:Date.now().toString()}:{},s===xe.GZipJS?{}:{compression:s}))},Or=[];Po&&Or.push({transport:"fetch",method:zu}),Cn&&Or.push({transport:"XHR",method(t){var e=Hu(t);if(e){var s=new Cn,r=e.encodedBody;s.open(t.method||"GET",e.url,!0);var i=r??{},n=i.contentType,o=i.body;Z(t.headers,function(a,l){s.setRequestHeader(l,a)}),n&&s.setRequestHeader("Content-Type",n),t.timeout&&(s.timeout=t.timeout),s.onreadystatechange=()=>{if(s.readyState===4){var a={statusCode:s.status,text:s.responseText};if(s.status===200)try{a.json=JSON.parse(s.responseText)}catch{}t.callback==null||t.callback(a)}},s.send(o)}}}),ke!=null&&ke.sendBeacon&&Or.push({transport:"sendBeacon",method:no});var oo=3e3;class Op{constructor(e,s){this.Xi=!0,this.tr=[],this.er=st((s==null?void 0:s.flush_interval_ms)||oo,250,5e3,C.createLogger("flush interval"),oo),this.ir=e}enqueue(e){this.tr.push(e),this.rr||this.nr()}unload(){this.sr();var e=this.tr.length>0?this.ar():{},s=Object.values(e);[...s.filter(r=>r.url.indexOf("/e")===0),...s.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.lr(b({},r,{transport:"sendBeacon"}))})}enable(){this.Xi=!1,this.nr()}nr(){var e=this;this.Xi||(this.rr=setTimeout(()=>{if(this.sr(),this.tr.length>0){var s=this.ar(),r=function(){var n=s[i],o=new Date().getTime();n.data&&B(n.data)&&Z(n.data,a=>{a.offset=Math.abs(a.timestamp-o),delete a.timestamp}),e.lr(n)};for(var i in s)r()}},this.er))}lr(e){try{this.ir(e)}catch(s){C.error(s)}}sr(){clearTimeout(this.rr),this.rr=void 0}ar(){var e={};return Z(this.tr,s=>{var r,i=s,n=(i?i.batchKey:null)||i.url;I(e[n])&&(e[n]=b({},i,{data:[]})),(r=e[n].data)==null||r.push(i.data)}),this.tr=[],e}}var Lp=["retriesPerformedSoFar"];class Bp{constructor(e){this.ur=!1,this.hr=3e3,this.tr=[],this._instance=e,this.tr=[],this.dr=!0,!I(m)&&"onLine"in m.navigator&&(this.dr=m.navigator.onLine,this.vr=()=>{this.dr=!0,this.cr()},this.pr=()=>{this.dr=!1},ie(m,"online",this.vr),ie(m,"offline",this.pr))}get length(){return this.tr.length}retriableRequest(e){var s=e.retriesPerformedSoFar,r=_c(e,Lp);at(s)&&(r.url=Fi(r.url,{retry_count:s})),this._instance._send_request(b({},r,{callback:i=>{if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(s??0))return void this.At(b({retriesPerformedSoFar:s},r));i.statusCode===0&&C.warn("Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after "+(s??0)+" retries.")}r.callback==null||r.callback(i)}}))}At(e){var s=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=s+1;var r=function(o){var a=3e3*Math.pow(2,o),l=a/2,u=Math.min(18e5,a),c=Math.random()-.5;return Math.ceil(u+c*(u-l))}(s),i=Date.now()+r;this.tr.push({retryAt:i,requestOptions:e});var n="Enqueued failed request for retry in "+r;navigator.onLine||(n+=" (Browser is offline)"),C.warn(n),this.ur||(this.ur=!0,this.gr())}gr(){if(this.mr&&clearTimeout(this.mr),this.tr.length===0)return this.ur=!1,void(this.mr=void 0);this.mr=setTimeout(()=>{this.dr&&this.tr.length>0&&this.cr(),this.gr()},this.hr)}cr(){var e=Date.now(),s=[],r=this.tr.filter(n=>e>n.retryAt||(s.push(n),!1));if(this.tr=s,r.length>0)for(var i of r)this.retriableRequest(i.requestOptions)}unload(){for(var e of(this.mr&&(clearTimeout(this.mr),this.mr=void 0),this.ur=!1,I(m)||(this.vr&&(m.removeEventListener("online",this.vr),this.vr=void 0),this.pr&&(m.removeEventListener("offline",this.pr),this.pr=void 0)),this.tr)){var s=e.requestOptions;try{this._instance._send_request(b({},s,{transport:"sendBeacon"}))}catch(r){C.error(r)}}this.tr=[]}}class Dp{constructor(e){this.yr=()=>{var s,r,i,n;this.br||(this.br={});var o=this.scrollElement(),a=this.scrollY(),l=o?Math.max(0,o.scrollHeight-o.clientHeight):0,u=a+((o==null?void 0:o.clientHeight)||0),c=(o==null?void 0:o.scrollHeight)||0;this.br.lastScrollY=Math.ceil(a),this.br.maxScrollY=Math.max(a,(s=this.br.maxScrollY)!==null&&s!==void 0?s:0),this.br.maxScrollHeight=Math.max(l,(r=this.br.maxScrollHeight)!==null&&r!==void 0?r:0),this.br.lastContentY=u,this.br.maxContentY=Math.max(u,(i=this.br.maxContentY)!==null&&i!==void 0?i:0),this.br.maxContentHeight=Math.max(c,(n=this.br.maxContentHeight)!==null&&n!==void 0?n:0)},this._instance=e}get _r(){return this._instance.config.scroll_root_selector}getContext(){return this.br}resetContext(){var e=this.br;return setTimeout(this.yr,0),e}startMeasuringScrollPosition(){ie(m,"scroll",this.yr,{capture:!0}),ie(m,"scrollend",this.yr,{capture:!0}),ie(m,"resize",this.yr)}scrollElement(){if(!this._r)return m==null?void 0:m.document.documentElement;var e=B(this._r)?this._r:[this._r];for(var s of e){var r=m==null?void 0:m.document.querySelector(s);if(r)return r}}wr(e){var s=e==="y"?"scrollTop":"scrollLeft";if(this._r){var r=this.scrollElement();return r&&r[s]||0}return m?e==="y"?m.scrollY||m.pageYOffset||m.document.documentElement.scrollTop||0:m.scrollX||m.pageXOffset||m.document.documentElement.scrollLeft||0:0}scrollY(){return this.wr("y")}scrollX(){return this.wr("x")}}var jp=t=>Au(t==null?void 0:t.config.mask_personal_data_properties,t==null?void 0:t.config.custom_personal_data_properties,t==null?void 0:t.config.disable_capture_url_hashes);class vl{constructor(e,s,r,i){this.kr=n=>{var o=this.Sr();if(!o||o.sessionId!==n){var a={sessionId:n,props:this.Cr(this._instance)};this.Mr.register({[Gn]:a})}},this._instance=e,this.Tr=s,this.Mr=r,this.Cr=i||jp,this.Tr.onSessionId(this.kr)}Sr(){return this.Mr.props[Gn]}getSetOnceProps(){var e,s=(e=this.Sr())==null?void 0:e.props;return s?"r"in s?$u(s,this._instance.config.disable_capture_url_hashes):{$referring_domain:s.referringDomain,$pathname:s.initialPathName,utm_source:s.utm_source,utm_campaign:s.utm_campaign,utm_medium:s.utm_medium,utm_content:s.utm_content,utm_term:s.utm_term}:{}}getSessionProps(){var e={};return Z(jo(this.getSetOnceProps()),(s,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+An(r)]=s}),e}}class Vo{on(e,s){return this.Er[e]||(this.Er[e]=[]),this.Er[e].push(s),()=>{this.Er[e]=this.Er[e].filter(r=>r!==s)}}emit(e,s){for(var r of this.Er[e]||[])r(s);for(var i of this.Er["*"]||[])i(e,s)}constructor(){this.Er={}}}var Rs=se("[SessionId]");class _l{on(e,s){return this.Ir.on(e,s)}constructor(e,s,r){var i;if(this.Pr=null,this.Rr=[],this.Ar=void 0,this.Fr=!1,this.Ir=new Vo,this.Lr=(u,c)=>!(!at(u)||!at(c))&&Math.abs(u-c)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode===dt)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ne=e.config,this.Mr=e.persistence,this.Or=void 0,this.Dr=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.$r=s||ut,this.Nr=r||ut;var n=this.Ne.persistence_name||this.Ne.token;if(this._sessionTimeoutMs=1e3*st(this.Ne.session_idle_timeout_seconds||1800,60,36e3,Rs.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.qr(),this.jr="ph_"+n+"_window_id",this.Br="ph_"+n+"_primary_window_exists",this.Hr()){var o=ce.H(this.jr),a=ce.H(this.Br);o&&!a?this.Or=o:ce.q(this.jr),ce.F(this.Br,!0)}if((i=this.Ne.bootstrap)!=null&&i.sessionID)try{var l=(u=>{var c=this.Ne.bootstrap.sessionID.replace(/-/g,"");if(c.length!==32)throw new Error("Not a valid UUID");if(c[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(c.substring(0,12),16)})();this.Ur(this.Ne.bootstrap.sessionID,new Date().getTime(),l)}catch(u){Rs.error("Invalid sessionID in bootstrap",u)}this.zr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return I(this.Rr)&&(this.Rr=[]),this.Rr.push(e),this.Dr&&e(this.Dr,this.Or),()=>{this.Rr=this.Rr.filter(s=>s!==e)}}Hr(){return this.Ne.persistence!=="memory"&&!this.Mr.xi&&ce.N()}Wr(e){e!==this.Or&&(this.Or=e,this.Hr()&&ce.F(this.jr,e))}Vr(){return this.Or?this.Or:this.Hr()?ce.H(this.jr):null}Zr(e){var s=this.Pr;return!$e(s)&&!$e(e)&&5e3>Math.abs(e-s)}Ur(e,s,r){var i=s!==this._sessionActivityTimestamp,n=!(e!==this.Dr||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=s,this.Dr=e,n&&!i||n&&this.Zr(s)||(this.Pr=s,this.Mr.register({[as]:[s,e,r]}))}Gr(){var e,s=(e=this.Ne)==null?void 0:e.persistence_save_debounce_ms;return at(s)&&s>0}Qr(){this.Gr()?this.Mr.refreshKey(as):(this.Mr.flush(),this.Mr.load())}Kr(){var e;if(!$e(this._sessionActivityTimestamp)&&this._sessionActivityTimestamp!==this.Pr){this.Qr();var s=this.Jr();s[1]===this.Dr&&s[2]===this._sessionStartTimestamp&&(this.Pr=this._sessionActivityTimestamp,this.Mr.register({[as]:[this._sessionActivityTimestamp,(e=this.Dr)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Mr.flush())}}Yr(){var e=this.Jr()[0],s=at(e)?e:0,r=at(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(s,r)}Xr(e){return this.Qr(),this.Lr(e,this.Yr())}Jr(){var e=this.Mr.props[as];return B(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Pr=null,clearTimeout(this.tn),this.tn=void 0,this.Ur(null,null,null)}destroy(){this.Fr=!0,this.Kr(),clearTimeout(this.tn),this.tn=void 0,this.Ar&&m&&(m.removeEventListener(ri,this.Ar,{capture:!1}),this.Ar=void 0),this.Rr=[]}zr(){this.Ar=()=>{this.Kr(),this.Hr()&&ce.q(this.Br)},ie(m,ri,this.Ar,{capture:!1})}checkAndGetSessionAndWindowId(e,s){if(e===void 0&&(e=!1),s===void 0&&(s=null),this.Ne.cookieless_mode===dt)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=s||new Date().getTime(),i=this.Jr(),n=i[1],o=i[2],a=this.Yr(),l=this.Vr(),u=at(o)&&Math.abs(r-o)>864e5,c=!1,d=!1,h=!n,p=n,f=!h&&!e&&this.Lr(r,a);if(f){(f=this.Xr(r))||Rs.info("cross-tab refresh kept the session alive",{sessionId:n});var g=this.Jr();n=g[1],o=g[2]}h||f||u?(n=this.$r(),l=this.Nr(),Rs.info("new session ID generated",{sessionId:n,windowId:l,changeReason:{noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u}}),o=r,c=!0):(l||(l=this.Nr(),c=!0),(d=n!==p)&&(Rs.info("adopted cross-tab session id",{sessionId:n,windowId:l}),c=!0));var v=at(a)&&e&&!u?a:r,_=at(o)?o:new Date().getTime();this.Wr(l),this.Ur(n,v,_),e||this.qr();var w={noSessionId:h,activityTimeout:f,sessionPastMaximumLength:u,crossTabAdoption:d};return c&&this.Rr.forEach(S=>S(n,l,w)),{sessionId:n,windowId:l,sessionStartTimestamp:_,changeReason:c?w:void 0,lastActivityTimestamp:a}}qr(){this.Fr||(clearTimeout(this.tn),this.tn=setTimeout(()=>{if(!this.Fr)if(this.Xr(new Date().getTime())){var e=this.Dr;this.resetSessionId(),this.Ir.emit("forcedIdleReset",{idleSessionId:e})}else this.qr()},1.1*this.sessionTimeoutMs))}}var qu=function(t,e){if(!t)return!1;var s=t.userAgent;if(s&&La(s,e))return!0;try{var r=t==null?void 0:t.userAgentData;if(r!=null&&r.brands&&r.brands.some(i=>La(i==null?void 0:i.brand,e)))return!0}catch{}return!!t.webdriver};function Vu(){return(Vu=X(function*(){var t=ke==null?void 0:ke.userAgentData;if(t!=null&&t.getHighEntropyValues)try{var e=yield t.getHighEntropyValues(["model"]),s=e==null?void 0:e.model;return W(s)&&s.length>0?s:void 0}catch(r){return void C.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",r)}})).apply(this,arguments)}var ui=function(t,e){if(!function(s){try{new RegExp(s)}catch{return!1}return!0}(e))return!1;try{return new RegExp(e).test(t)}catch{return!1}};function pn(t,e,s){return ls({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:s})}var Gu={exact:(t,e)=>e.some(s=>t.some(r=>s===r)),is_not:(t,e)=>e.every(s=>t.every(r=>s!==r)),regex:(t,e)=>e.some(s=>t.some(r=>ui(s,r))),not_regex:(t,e)=>e.every(s=>t.every(r=>!ui(s,r))),icontains:(t,e)=>e.map(Sr).some(s=>t.map(Sr).some(r=>s.includes(r))),not_icontains:(t,e)=>e.map(Sr).every(s=>t.map(Sr).every(r=>!s.includes(r))),gt:(t,e)=>e.some(s=>{var r=parseFloat(s);return!isNaN(r)&&t.some(i=>r>parseFloat(i))}),lt:(t,e)=>e.some(s=>{var r=parseFloat(s);return!isNaN(r)&&t.some(i=>rt.toLowerCase();function Ku(t,e){return!t||Object.entries(t).every(s=>{var r=s[1],i=e==null?void 0:e[s[0]];if(I(i)||$e(i))return!1;var n=[String(i)],o=Gu[r.operator];return!!o&&o(r.values,n)})}var ao="custom",yl="i.posthog.com",Up=/^\/static\//;class Hp{constructor(e){this.en={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,s=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return s||(s=this.apiHost.replace("."+yl,".posthog.com")),s==="https://app.posthog.com"?"https://us.posthog.com":s}get region(){return this.en[this.apiHost]||(this.en[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":ao),this.en[this.apiHost]}rn(e){if(Up.test(e)){var s=this.instance.config.asset_host;if(typeof s=="string")return s.trim().replace(/\/$/,"")||void 0}}endpointFor(e,s){if(s===void 0&&(s=""),s&&(s=s[0]==="/"?s:"/"+s),e==="ui")return this.uiHost+s;if(e==="flags")return this.flagsApiHost+s;if(e==="assets"){var r=this.rn(s);if(r)return""+r+s}if(this.region===ao)return this.apiHost+s;var i=yl+s;switch(e){case"assets":return"https://"+this.region+"-assets."+i;case"api":return"https://"+this.region+"."+i}}}function Ju(t){var e;return!((e=t.conditions)==null||(e=e.events)==null||(e=e.values)==null||!e.length)}var V=se("[Surveys]"),Yu="seenSurvey_",Zu=t=>{try{var e=(s=>((r,i)=>""+Yu+function(n){return n.current_iteration&&n.current_iteration>0?n.id+"_"+n.current_iteration:n.id}(i))(0,s))(t);if(localStorage.getItem(e))return;localStorage.setItem(e,"true")}catch(s){V.error("Failed to persist survey seen state",s)}},Wp=[ln.Popover,ln.Widget,ln.API],zp={ignoreConditions:!1,ignoreDelay:!1,displayType:to.Popover},qp=se("[PostHog ExternalIntegrations]"),Vp={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Gp{constructor(e){this._instance=e}ai(e,s){var r;(r=R.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,i=>{if(i)return qp.error("failed to load script",i);s()})}startIfEnabledOrStop(){var e=this,s=function(){var n,o,a,l=r[0],u=r[1];!u||(n=R.__PosthogExtensions__)!=null&&(n=n.integrations)!=null&&n[l]||e.ai(Vp[l],()=>{var c;(c=R.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[l])==null||c.start(e._instance)}),!u&&(o=R.__PosthogExtensions__)!=null&&(o=o.integrations)!=null&&o[l]&&((a=R.__PosthogExtensions__)==null||(a=a.integrations)==null||(a=a[l])==null||a.stop())};for(var r of Object.entries((i=this._instance.config.integrations)!==null&&i!==void 0?i:{})){var i;s()}}}class Kp{constructor(e,s){this.rt=e,this.nn=s,this.sn=new Map,this.an=!1}add(e){var s=this;return X(function*(){if(s.an)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(s.sn.has(e.name))throw new Error('Browser extension "'+e.name+'" is already registered');s.sn.set(e.name,e);try{var r=e.setup(s.nn);r&&(yield r)}catch(n){var i=s.sn.get(e.name)===e;i&&s.sn.delete(e.name),s.rt.error('Failed to set up browser extension "'+e.name+'"',n),i&&s.ln(e)}})()}dispose(){if(!this.an){this.an=!0;var e=Array.from(this.sn.values()).reverse();for(var s of(this.sn.clear(),e))this.ln(s)}}ln(e){try{var s=e.dispose==null?void 0:e.dispose();s&&Se(s.then)&&s.then(void 0,r=>{this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)})}catch(r){this.rt.error('Failed to dispose browser extension "'+e.name+'"',r)}}}class Jp{constructor(e){this._instance=e}initialize(){}get(e){var s=this._instance.persistence;if(typeof e=="string")return s==null?void 0:s.get_property(e);var r={};for(var i of e){var n=s==null?void 0:s.get_property(i);I(n)||(r[i]=n)}return r}set(e,s){var r;(r=this._instance.persistence)==null||r.register(typeof e=="string"?{[e]:s}:e)}remove(e){var s;(s=this._instance.persistence)==null||s.unregister(e)}}var wl="extensionsRemoteConfig";class Yp{constructor(e){this.an=!1,this.instance=e,this.rt=C,this.un=e.hn,this.kv=new Jp(e),this.onEvent=s=>Er(this.instance.on("eventCaptured",r=>{try{s({event:r.event,properties:r.properties})}catch(i){this.rt.error("Browser extension event listener failed",i)}})),this.onRemoteConfig=s=>{if(this.an)return Er(()=>{});var r=n=>{try{s(n)}catch(o){this.rt.error("Browser extension remote config listener failed",o)}},i=this.instance.dn.on(wl,r);return this.un&&r(this.un),Er(i)},this.vn=new Kp(C.createLogger("[BrowserExtensions]"),this)}get logger(){return this.rt}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property(Qs))!==null&&e!==void 0?e:this.distinctId}get deviceId(){var e=this.instance.get_property(Qs);return typeof e=="string"?e:void 0}get library(){return{name:Y.LIB_NAME,version:Y.LIB_VERSION}}get initialPersonProperties(){var e,s;return(e=(s=this.instance.persistence)==null?void 0:s.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,s,r,i,n=(e=this.instance.sessionManager)==null?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(s=n==null?void 0:n.sessionId)!==null&&s!==void 0?s:"",windowId:(r=n==null?void 0:n.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(i=n==null?void 0:n.sessionStartTimestamp)!==null&&i!==void 0?i:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get projectToken(){return this.instance.config.token}add(e){return this.vn.add(e)}capture(e,s,r){var i=this;return X(function*(){r?i.instance.capture(e,s,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):i.instance.capture(e,s)})()}registerDynamicEventProperties(e){return Er(this.instance.cn(e))}handleRemoteConfig(e){this.an||(this.un=e,this.instance.dn.emit(wl,e))}sendRequest(e,s){var r=this;return X(function*(){var i;s===void 0&&(s={});var n=r.instance.requestRouter.endpointFor((i=s.target)!==null&&i!==void 0?i:"api",e),o={method:s.method,url:s.query?Fi(n,s.query):n,data:s.body,headers:s.headers,timeout:s.timeoutMs,fireCallbackOnDrop:!0,transport:s.transport,compression:s.compression,timestampMode:s.sentAt};return s.transport==="sendBeacon"?(r.instance._send_request(o),{statusCode:202}):new Promise(a=>{o.callback=a,r.instance._send_request(o)})})()}dispose(){this.an||(this.an=!0,this.vn.dispose())}}var Ks={},fn=0,di=()=>{},bl='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Ts="Surveys module not available",El="sanitize_properties is deprecated. Use before_send instead",Xu="Invalid value for property_denylist config: ",Zp=["token","distinct_id",nu],ns="posthog",Qu=!Tp&&(Pe==null?void 0:Pe.indexOf("MSIE"))===-1&&(Pe==null?void 0:Pe.indexOf("Mozilla"))===-1,gn=t=>{var e;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Xh(F==null?void 0:F.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:di,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:re&&W(re==null?void 0:re.search)&&re.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,disable_external_dependency_loading:!1,strict_script_versioning:!1,enable_recording_console_log:void 0,secure_cookie:(m==null||(e=m.location)==null?void 0:e.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error(s){C.error("Bad HTTP status: "+s.statusCode+" "+s.text)},get_device_id:s=>s,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Zn,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:oo},error_tracking:{},_onCapture:di},(s=>({rageclick:s&&s>="2026-05-30"?{content_ignorelist:up,ignore_text_selection:!0}:!s||"2025-11-30">s||{content_ignorelist:!0},capture_pageview:!s||"2025-05-24">s||"history_change",session_recording:s&&s>="2026-06-25"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6},streamNetworkBody:!0}:s&&s>="2026-05-30"?{strictMinimumDuration:!0,canvasCapture:{resolutionScale:.6}}:s&&s>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:s&&s>="2026-01-30"?"head":"body",internal_or_test_user_hostname:s&&s>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:s&&s>="2026-05-30"?250:0,split_storage:!(!s||"2026-05-30">s),detect_google_search_app:!(!s||"2026-05-30">s),disable_capture_url_hashes:!(!s||"2026-06-25">s)}))(t))},Xp=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"]],Sl=t=>{var e={};for(var s of Xp){var r=s[0],i=s[1];I(t[r])||(e[i]=t[r])}var n=ee({},e,t),o=t.__preview_external_dependency_versioned_paths;return I(o)||(I(t.strict_script_versioning)&&(n.strict_script_versioning=!!o),W(o)&&I(t.asset_host)&&(n.asset_host=o)),B(t.property_blacklist)&&(I(t.property_denylist)?n.property_denylist=t.property_blacklist:B(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:C.error(Xu+t.property_denylist)),n};class Qp{constructor(){this.__forceAllowLocalhost=!1}get fn(){return this.__forceAllowLocalhost}set fn(e){C.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Te{pn(e,s){if(e){var r=this.sn.indexOf(e);r!==-1&&this.sn.splice(r,1)}return this.sn.push(s),s.initialize==null||s.initialize(),s}gn(){return this.config.cookieless_mode===dt||this.config.cookieless_mode===jt&&this.consent.isRejected()}get decideEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){var e;this.webPerformance=new Qp,this.mn=!1,this.version=Y.LIB_VERSION,this.yn=new Set,this.bn="",this.dn=new Vo,this.sn=[],this._n=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=gn(),this.SentryIntegration=_p,this.sentryIntegration=r=>function(i,n){var o=Su(i,n);return{name:Eu,processEvent:a=>o(a)}}(this,r),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.wn=!1,this.kn=null,this.xn=null,this.Sn=null,this.scrollManager=new Dp(this),this.pageViewManager=new ll(this),this.rateLimiter=new Cp(this),this.requestRouter=new Hp(this),this.consent=new np(this),this.externalIntegrations=new Gp(this);var s=(e=Te.__defaultExtensionClasses)!==null&&e!==void 0?e:{};this.featureFlags=s.featureFlags&&new s.featureFlags(this),this.toolbar=s.toolbar&&new s.toolbar(this),this.surveys=s.surveys&&new s.surveys(this),this.conversations=s.conversations&&new s.conversations(this),this.logs=s.logs&&new s.logs(this),this.metrics=s.metrics&&new s.metrics(this),this.experiments=s.experiments&&new s.experiments(this),this.exceptions=s.exceptions&&new s.exceptions(this),this.people={set:(r,i,n)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(o),n==null||n({})},set_once:(r,i,n)=>{var o=W(r)?{[r]:i}:r;this.setPersonProperties(void 0,o),n==null||n({})}},this.on("eventCaptured",r=>C.info('send "'+(r==null?void 0:r.event)+'"',r))}init(e,s,r){if(r&&r!==ns){var i,n=(i=Ks[r])!==null&&i!==void 0?i:new Te;return n._init(e,s,r),Ks[r]=n,Ks[ns][r]=n,n}return this._init(e,s,r)}_init(e,s,r){var i,n;s===void 0&&(s={});var o,a=W(e)?e.trim():"";if(!a)return C.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return a!==((o=this.config)==null?void 0:o.token)?console.warn("[PostHog.js]","You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('"+a+"', { ... }, 'project2')"):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=gn(s.defaults),s.debug=this.Cn(s.debug),this.Mn=s,this.Tn=[],s.person_profiles?this.xn=s.person_profiles:s.process_person&&(this.xn=s.process_person);var l=gn(s.defaults),u=Sl(s),c=ee({},l,u,{name:r,token:a});te(l.rageclick)&&te(u.rageclick)&&(c.rageclick=ee({},l.rageclick,u.rageclick)),te(l.session_recording)&&te(u.session_recording)&&(c.session_recording=ee({},l.session_recording,u.session_recording)),this.set_config(c),this.config.on_xhr_error&&C.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=s.disable_compression?void 0:xe.GZipJS;var d=this.En();if(this.persistence=new an(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new an(b({},this.config,{persistence:"sessionStorage"}),d,!1),this.bn="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&ce.N()){var h=ce.H(this.bn);B(h)&&h.forEach(P=>{W(P)&&this.yn.add(P)})}else ce.q(this.bn);var p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.In=new Op(P=>this.Pn(P),this.config.request_queue_config),this.Rn=new Bp(this),this.__request_queue=[];var g=this.gn();if(g||(this.sessionManager=new _l(this),this.sessionPropsManager=new vl(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((P,M,E)=>{(E!=null&&E.activityTimeout||E!=null&&E.sessionPastMaximumLength||E!=null&&E.crossTabAdoption)&&this.An()})),this.Fn(),this.config.__preview_deferred_init_extensions?(C.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Ln(g)},0)):(C.info("Initializing extensions synchronously"),this.Ln(g)),Y.DEBUG=Y.DEBUG||this.config.debug,Y.DEBUG&&C.info("Starting in debug mode",{this:this,config:s,thisC:b({},this.config),p,s:f}),!this.config.identity_distinct_id||(i=s.bootstrap)!=null&&i.distinctID||(s.bootstrap=b({},s.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((n=s.bootstrap)==null?void 0:n.distinctID)!==void 0){var v=s.bootstrap.distinctID,_=this.get_distinct_id(),w=this.persistence.get_property(He);if(s.bootstrap.isIdentifiedID&&_!=null&&_!==v&&w===Qt)this.identify(v);else if(s.bootstrap.isIdentifiedID&&_!=null&&_!==v&&w===$t)C.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{var S=this.config.get_device_id(ut()),k=s.bootstrap.isIdentifiedID?S:v;this.persistence.set_property(He,s.bootstrap.isIdentifiedID?$t:Qt),this.register({distinct_id:v,$device_id:k})}}if(g)this.register_once({distinct_id:vr,$device_id:null},"");else if(!this.get_distinct_id()){var x=this.config.get_device_id(ut());this.register_once({distinct_id:x,$device_id:x},""),this.persistence.set_property(He,Qt)}return ie(m,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),s.segment?function(P,M){var E=P.config.segment;if(!E)return M();(function(A,$){var N=A.config.segment;if(!N)return $();var T=J=>{var z=()=>J.anonymousId()||ut();A.config.get_device_id=z,J.id()&&(A.register({distinct_id:J.id(),$device_id:z()}),A.persistence.set_property(He,$t)),$()},O=N.user();"then"in O&&Se(O.then)?O.then(T):T(O)})(P,()=>{E.register((A=>{typeof Promise<"u"&&Promise.resolve||nn.warn("This browser does not have Promise support, and can not use the segment integration");var $=(N,T)=>{if(!T)return N;N.event.userId||N.event.anonymousId===A.get_distinct_id()||(nn.info("No userId set, resetting PostHog"),A.reset()),N.event.userId&&N.event.userId!==A.get_distinct_id()&&(nn.info("UserId set, identifying with PostHog"),A.identify(N.event.userId));var O=A.calculateEventProperties(T,N.event.properties);return N.event.properties=Object.assign({},O,N.event.properties),N};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:N=>$(N,N.event.event),page:N=>$(N,is),identify:N=>$(N,tn),screen:N=>$(N,"$screen")}})(P)).then(()=>{M()})})}(this,()=>this.On()):this.On(),Se(this.config._onCapture)&&this.config._onCapture!==di&&(C.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",P=>this.config._onCapture(P.event,P))),this.config.ip&&C.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||function(){return Vu.apply(this,arguments)}().then(P=>{P&&this.register({[Qi]:P})}).catch(di),this}Fn(){var e,s,r,i,n,o,a=(e=(s=this.config.__extensionClasses)==null?void 0:s.featureFlags)!==null&&e!==void 0?e:(r=Te.__defaultExtensionClasses)==null?void 0:r.featureFlags;a&&(this.featureFlags&&this.featureFlags instanceof a||((i=this.Dn)==null||i.call(this),this.Dn=void 0,this.featureFlags=new a(this)),Se(this.featureFlags.onReloading)&&Se(this.featureFlags.setup)?this.Dn||(this.Dn=this.featureFlags.onReloading(()=>{this.dn.emit("featureFlagsReloading",!0)}),this.$n().add(this.featureFlags)):(n=(o=this.featureFlags).initialize)==null||n.call(o))}Ln(e){var s,r,i,n,o,a,l,u=performance.now(),c=b({},Te.__defaultExtensionClasses,this.config.__extensionClasses),d=[];c.exceptions&&this.sn.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new c.exceptions(this)),c.historyAutocapture&&this.sn.push(this.historyAutocapture=new c.historyAutocapture(this)),c.tracingHeaders&&this.sn.push(this.tracingHeaders=new c.tracingHeaders(this)),c.siteApps&&this.sn.push(this.siteApps=new c.siteApps(this)),c.sessionRecording&&!e&&this.sn.push(this.sessionRecording=new c.sessionRecording(this)),this.config.disable_scroll_properties||d.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),c.autocapture&&this.sn.push(this.autocapture=new c.autocapture(this)),c.surveys&&this.sn.push(this.surveys=(r=this.surveys)!==null&&r!==void 0?r:new c.surveys(this)),c.logs&&this.sn.push(this.logs=(i=this.logs)!==null&&i!==void 0?i:new c.logs(this)),c.metrics&&this.sn.push(this.metrics=(n=this.metrics)!==null&&n!==void 0?n:new c.metrics(this)),c.conversations&&this.sn.push(this.conversations=(o=this.conversations)!==null&&o!==void 0?o:new c.conversations(this)),c.productTours&&this.sn.push(this.productTours=new c.productTours(this)),c.heatmaps&&this.sn.push(this.heatmaps=new c.heatmaps(this)),c.webVitalsAutocapture&&this.sn.push(this.webVitalsAutocapture=new c.webVitalsAutocapture(this)),c.exceptionObserver&&this.sn.push(this.exceptionObserver=new c.exceptionObserver(this)),c.deadClicksAutocapture&&this.sn.push(this.deadClicksAutocapture=new c.deadClicksAutocapture(this,vp)),c.toolbar&&this.sn.push(this.toolbar=(a=this.toolbar)!==null&&a!==void 0?a:new c.toolbar(this)),c.experiments&&this.sn.push(this.experiments=(l=this.experiments)!==null&&l!==void 0?l:new c.experiments(this)),this.sn.forEach(h=>{h.initialize&&d.push(()=>{h.initialize==null||h.initialize()})}),d.push(()=>{if(this.Nn){var h=this.Nn;this.Nn=void 0,this.sn.forEach(p=>p.onRemoteConfig==null?void 0:p.onRemoteConfig(h))}}),this.qn(d,u)}qn(e,s){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-s>=30&&e.length>0)return void setTimeout(()=>{this.qn(e,s)},0);var r=e.shift();if(r)try{r()}catch(n){C.error("Error initializing extension:",n)}}var i=Math.round(performance.now()-s);this.register_for_session({[ou]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[au]:i}),this.config.__preview_deferred_init_extensions&&C.info("PostHog extensions initialized ("+i+"ms)")}Zi(e){var s;if(!F||!F.body)return C.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.Zi(e)},500);if(this.config.__preview_deferred_init_extensions&&(this.Nn=e),this.hn=e,this.compression=void 0,e.ok){var r,i=e.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=L(i.supportedCompression,xe.GZipJS)?xe.GZipJS:L(i.supportedCompression,xe.Base64)?xe.Base64:void 0),(r=i.analytics)!=null&&r.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.xn?this.xn:Zn}),(s=this.jn)==null||s.handleRemoteConfig(e),this.sn.forEach(n=>n.onRemoteConfig==null?void 0:n.onRemoteConfig(e))}On(){try{this.config.loaded(this)}catch(r){C.critical("`loaded` function failed",r)}if(this.Bn(),this.config.internal_or_test_user_hostname&&re!=null&&re.hostname){var e=re.hostname,s=this.config.internal_or_test_user_hostname;(typeof s=="string"?e===s:s.test(e))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.gn())&&this.Hn()},1),this.Un=new Tu(this),this.Un.load()}Bn(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.In)==null||e.enable())}_dom_loaded(){this.is_capturing()&&_r(this.__request_queue,e=>this.Pn(e)),this.__request_queue=[],this.Bn()}_handle_unload(){var e,s,r,i,n;(e=this.surveys)==null||e.handlePageUnload==null||e.handlePageUnload(),(s=this.metrics)==null||s.flush("sendBeacon"),this.config.request_batching?(this.zn()&&this.capture(en),(r=this.logs)==null||r.flushLogs("sendBeacon"),(i=this.In)==null||i.unload(),(n=this.Rn)==null||n.unload()):this.zn()&&this.capture(en,null,{transport:"sendBeacon"})}_send_request(e){this.__loaded?Qu?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)?e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:429})):(e.transport=e.transport||this.config.api_transport,e.headers=b({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,(I(this.config.disable_beacon)?this.config.__preview_disable_beacon:this.config.disable_beacon)&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(s=>{var r,i,n,o=b({},s);o.timeout=o.timeout||6e4;var a,l,u,c,d,h=(r=o.transport)!==null&&r!==void 0?r:"fetch";h==="sendBeacon"&&I(o.compression)&&o.data&&(o.compression=xe.Base64),o.method==="POST"&&o.data&&(o.timestampMode==="capture-body"?o.data={api_key:(l=(d=(c=B(a=o.data)?a:[a])[0])==null||(u=d.properties)==null?void 0:u.token)!==null&&l!==void 0?l:d==null?void 0:d.token,batch:c,sent_at:new Date().toISOString()}:o.timestampMode==="body"&&(o.data=function(v,_){return _===void 0&&(_=new Date().toISOString()),B(v)?v.map(w=>b({},w,{sent_at:_})):b({},v,{sent_at:_})}(o.data))),o.url=ml(o.url,o.method,o.compression,o.timestampMode);var p=Or.filter(v=>!o.disableTransport||!v.transport||!o.disableTransport.includes(v.transport)),f=(i=(n=function(v,_){for(var w=0;v.length>w;w++)if(v[w].transport===h)return v[w]}(p))==null?void 0:n.method)!==null&&i!==void 0?i:p[0].method;if(!f)throw new Error("No available transport method");var g=v=>{try{f(v)}catch(_){Wu(_)?C.warn(_):C.error(_),o.callback==null||o.callback({statusCode:0,error:_})}};h!=="sendBeacon"&&o.data&&o.compression===xe.GZipJS&&eh&&typeof Promise<"u"&&!Mr?Np(o).then(v=>{g(v)}).catch(v=>{if(Oa(v))return Mr=!0,void g(b({},o,{compression:void 0,url:ml(s.url,s.method,void 0,s.timestampMode)}));(_=>{if(!_||typeof _!="object")return!1;var w="name"in _?String(_.name):"";return Oa(_)||w===yc})(v)&&(Mr=!0),g(o)}):f(o)})(b({},e,{callback:s=>{var r,i;this.rateLimiter.checkForLimiting(s),400>s.statusCode||(r=(i=this.config).on_request_error)==null||r.call(i,s),e.callback==null||e.callback(s)}}))):e.fireCallbackOnDrop&&(e.callback==null||e.callback({statusCode:0}))}Pn(e){this.Rn?this.Rn.retriableRequest(e):this._send_request(e)}_execute_array(e){fn++;try{var s,r=[],i=[],n=[];_r(e,a=>{if(a)if(B(s=a[0]))n.push(a);else if(Se(a))try{a.call(this)}catch(l){C.error("Error executing queued PostHog call",a,l)}else B(a)&&s==="alias"?r.push(a):B(a)&&s.indexOf("capture")!==-1&&Se(this[s])?n.push(a):i.push(a)});var o=function(a,l){_r(a,function(u){try{if(B(u[0])){var c=l;Z(u,function(d){c=c[d[0]].apply(c,d.slice(1))})}else l[u[0]].apply(l,u.slice(1))}catch(d){C.error("Error executing queued PostHog call",u,d)}})};o(r,this),o(i,this),o(n,this)}finally{fn--}}push(e){if(fn>0&&B(e)&&W(e[0])){var s=Te.prototype[e[0]];Se(s)&&s.apply(this,e.slice(1))}else this._execute_array([e])}capture(e,s,r){var i,n,o,a,l;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.In){if(this.is_capturing())if(!I(e)&&W(e)){var u=!this.config.opt_out_useragent_filter&&this._is_bot();if(!u||this.config.__preview_capture_bot_pageviews){var c=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(c==null||!c.isRateLimited){s!=null&&s.$current_url&&!W(s==null?void 0:s.$current_url)&&(C.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),s==null||delete s.$current_url),e!=="$exception"||r!=null&&r.Wn||C.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();var d=new Date,h=(r==null?void 0:r.timestamp)||d,p=Ua(r==null?void 0:r.uuid,ut),f={uuid:p,event:e,properties:this.calculateEventProperties(e,s||{},h,p)};e===is&&this.config.__preview_capture_bot_pageviews&&u&&(f.event="$bot_pageview",f.properties.$browser_type="bot"),c&&(f.properties.$lib_rate_limit_remaining_tokens=c.remainingTokens);var g=e==="$feature_flag_called"&&f.properties.$feature_flag_has_experiment===!1&&this.get_property(Xr)===!0;r!=null&&r.$set&&!g&&(f.$set=r==null?void 0:r.$set);var v=r==null?void 0:r.$unset;v&&(f.$unset=v);var _,w,S,k=g?void 0:this.Vn(r==null?void 0:r.$set_once,e!==Ga,e===tn);if(k&&(f.$set_once=k),r!=null&&r._noTruncate||(n=this.config.properties_string_max_length,o=f,a=T=>W(T)?T.slice(0,n):T,l=new Set,f=function T(O,J){if(O!==Object(O))return a?a(O):O;if(!l.has(O)){var z;if(l.add(O),B(O))z=[],_r(O,oe=>{z.push(T(oe))});else{var H={};Z(O,(oe,pe)=>{l.has(oe)||(H[pe]=T(oe))}),z=H}return z}}(o)),f.timestamp=h,I(r==null?void 0:r.timestamp)||(f.properties.$event_time_override_provided=!0,f.properties.$event_time_override_system_time=d),g&&(f.properties=function(T,O){O===void 0&&(O=[]);var J={},z=H=>{T[H]!==void 0&&(J[H]=T[H])};return th.forEach(z),O.forEach(z),J}(f.properties,Zp)),e===pt.DISMISSED||e===pt.SENT){var x=s==null?void 0:s[cn.SURVEY_ID],P=s==null?void 0:s[cn.SURVEY_ITERATION];Zu({id:x,current_iteration:P}),f.$set=b({},f.$set,{[(_={id:x,current_iteration:P},w=e===pt.SENT?"responded":"dismissed",S="$survey_"+w+"/"+_.id,_.current_iteration&&_.current_iteration>0&&(S="$survey_"+w+"/"+_.id+"/"+_.current_iteration),S)]:!0})}else e===pt.SHOWN&&(f.$set=b({},f.$set,{[cn.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if(e===Ip.SHOWN){var M=s==null?void 0:s[ul.TOUR_TYPE];M&&(f.$set=b({},f.$set,{[ul.TOUR_LAST_SEEN_DATE+"/"+M]:new Date().toISOString()}))}var E=b({},f.properties.$set,f.$set);if(gt(E)||this.setPersonPropertiesForFlags(E),!D(this.config.before_send)){var A=this.Pt(f);if(!A)return;(f=A).uuid=Ua(f.uuid,ut)}this.dn.emit("eventCaptured",f);var $=(i=r==null?void 0:r._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),N={method:"POST",url:$,data:f,compression:"best-available",timestampMode:(r==null?void 0:r._batchKey)==="recordings"||/\/s\/(?:\?|$)/.test($)?"body":"capture-body",batchKey:r==null?void 0:r._batchKey,transport:r==null?void 0:r.transport};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Pn(N):this.In.enqueue(N),f}C.critical("This capture call is ignored due to client rate limiting.")}}else C.error("No event name provided to posthog.capture")}else C.uninitializedWarning("posthog.capture")}_addCaptureHook(e){return this.on("eventCaptured",s=>e(s.event,s))}$n(){var e;return(e=this.jn)!==null&&e!==void 0?e:this.jn=new Yp(this)}cn(e){this._n.push(e);var s=!0;return()=>{if(s){s=!1;var r=this._n.indexOf(e);r!==-1&&this._n.splice(r,1)}}}calculateEventProperties(e,s,r,i,n){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return s;var o=n?void 0:this.persistence.remove_event_timer(e),a=b({},s);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.gn()&&(a[nu]=!0),e==="$snapshot"){var l=b({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!W(a.distinct_id)&&!he(a.distinct_id)||$n(a.distinct_id))&&C.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var u,c=function(x,P,M,E){var A,$,N,T;if(E===void 0&&(E=!1),!Pe)return{};var O,J=x?[...vs,...P||[]]:[],z=function(pr){for(var je=0;Da.length>je;je++){var fr=Da[je],Zt=fr[1],Xt=fr[0].exec(pr),ks=Xt&&(Se(Zt)?Zt(Xt,pr):Zt);if(ks)return ks}return["",""]}(Pe),H=z[0],oe=z[1],pe=(O=typeof navigator<"u"?navigator:void 0)!=null&&O.brave?{brave:!0}:{},Ie={};I(M)||(Ie.detectGoogleSearchApp=M);var _e={},Ce=(A=navigator)==null||(A=A.userAgentData)==null?void 0:A.platform,Re=($=navigator)==null?void 0:$.maxTouchPoints,ae=m==null||(N=m.screen)==null?void 0:N.width,me=m==null||(T=m.screen)==null?void 0:T.height,ge=m==null?void 0:m.devicePixelRatio;I(Ce)||(_e.userAgentDataPlatform=Ce),I(Re)||(_e.maxTouchPoints=Re),I(ae)||(_e.screenWidth=ae),I(me)||(_e.screenHeight=me),I(ge)||(_e.devicePixelRatio=ge);var Je,At,de,Ve,Et,xs,De,Fe,hr=ee(jo({$os:H,$os_version:oe,$browser:zc(Pe,navigator.vendor,pe,Ie),$device:ja(Pe),$device_type:(At=Pe,de=_e,Fe=ja(At),Fe===Ic||Fe===kc||Fe==="Kobo"||Fe==="Kindle Fire"||Fe===Dc?ps:Fe===Zs||Fe===us||Fe===Xs||Fe===Tn?"Console":Fe===Fc?"Wearable":Fe?Le:(de==null?void 0:de.userAgentDataPlatform)==="Android"&&((Ve=de==null?void 0:de.maxTouchPoints)!==null&&Ve!==void 0?Ve:0)>0?600>Math.min((Et=de==null?void 0:de.screenWidth)!==null&&Et!==void 0?Et:0,(xs=de==null?void 0:de.screenHeight)!==null&&xs!==void 0?xs:0)/((De=de==null?void 0:de.devicePixelRatio)!==null&&De!==void 0?De:1)?Le:ps:"Desktop"),$timezone:Ru(),$timezone_offset:Sp()}),{$current_url:tr(E?It(re==null?void 0:re.href):re==null?void 0:re.href,J,sr),$host:re==null?void 0:re.host,$pathname:re==null?void 0:re.pathname,$raw_user_agent:Pe.length>1e3?Pe.substring(0,997)+"...":Pe,$browser_version:wh(Pe,navigator.vendor,pe,Ie),$browser_language:cl(),$browser_language_prefix:(Je=cl(),typeof Je=="string"?Je.split("-")[0]:void 0),$screen_height:m==null?void 0:m.screen.height,$screen_width:m==null?void 0:m.screen.width,$viewport_height:m==null?void 0:m.innerHeight,$viewport_width:m==null?void 0:m.innerWidth,$lib:Y.LIB_NAME,$lib_version:Y.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return Y.SDK_DIST_CHANNEL&&(hr.$sdk_dist_channel=Y.SDK_DIST_CHANNEL),hr}(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){var d=this.sessionManager.checkAndGetSessionAndWindowId(n,r.getTime()),h=d.windowId;a.$session_id=d.sessionId,a.$window_id=h}this.sessionPropsManager&&ee(a,this.sessionPropsManager.getSessionProps());try{var p;this.sessionRecording&&ee(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(p=this.Rn)==null?void 0:p.length}catch(x){a.$sdk_debug_error_capturing_properties=String(x)}if(this.requestRouter.region===ao&&(a.$lib_custom_api_host=this.config.api_host),u=e!==is||n?e!==en||n?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=ee(a,u),e===is&&F&&(a.title=F.title),!I(o)){var f=r.getTime()-o;a.$duration=parseFloat((f/1e3).toFixed(3))}Pe&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");var g=this.persistence.properties(),v=this.sessionPersistence.properties();Z(["$referrer","$referring_domain"],x=>{x in g&&delete v[x]});var _={};if(this._n.length>0)for(var w of this._n.slice())try{ee(_,w())}catch(x){C.error("Failed to produce browser extension event properties",x)}(a=ee({},c,g,v,b({},_,a))).$is_identified=this._isIdentified(),B(this.config.property_denylist)?Z(this.config.property_denylist,function(x){delete a[x]}):C.error(Xu+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var S=this.config.sanitize_properties;S&&(C.error(El),a=S(a,e));var k=this.Zn();return a.$process_person_profile=k,k&&!n&&this.Gn("_calculate_event_properties"),a}Vn(e,s,r){var i;if(s===void 0&&(s=!0),r===void 0&&(r=!1),!this.persistence||!this.Zn()||this.mn&&!r)return e;var n=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)==null?void 0:i.getSetOnceProps(),a=ee({},n,o||{},e||{}),l=this.config.sanitize_properties;return l&&(C.error(El),a=l(a,"$set_once")),s&&(this.mn=!0),gt(a)?void 0:a}register(e,s){var r;(r=this.persistence)==null||r.register(e,s)}register_once(e,s,r){var i;(i=this.persistence)==null||i.register_once(e,s,r)}register_for_session(e){var s;(s=this.sessionPersistence)==null||s.register(e),Object.keys(e).forEach(r=>this.yn.add(r)),this.Qn()}unregister(e){var s;(s=this.persistence)==null||s.unregister(e)}unregister_for_session(e){var s;(s=this.sessionPersistence)==null||s.unregister(e),this.yn.delete(e),this.Qn()}Kn(e,s){this.register({[e]:s})}An(){this.yn.forEach(e=>{var s;(s=this.sessionPersistence)==null||s.unregister(e)}),this.yn.clear(),this.Qn()}Qn(){var e;if(this.bn)if(this.config.persistence==="memory"||(e=this.sessionPersistence)!=null&&e.xi||!ce.N())ce.q(this.bn);else{var s=[];this.yn.forEach(r=>s.push(r)),s.length>0?ce.F(this.bn,s):ce.q(this.bn)}}getFeatureFlag(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlag(e,s)}getFeatureFlagPayload(e){var s;return(s=this.featureFlags)==null?void 0:s.getFeatureFlagPayload(e)}getFeatureFlagResult(e,s){var r;return(r=this.featureFlags)==null?void 0:r.getFeatureFlagResult(e,s)}getAllFeatureFlags(){var e,s;return(e=(s=this.featureFlags)==null?void 0:s.getAllFeatureFlags())!==null&&e!==void 0?e:[]}isFeatureEnabled(e,s){var r,i;return(r=(i=this.featureFlags)==null?void 0:i.isFeatureEnabled(e,s))!==null&&r!==void 0?r:s==null?void 0:s.defaultValue}reloadFeatureFlags(){var e;(e=this.featureFlags)==null||e.reloadFeatureFlags()}updateFlags(e,s,r){var i;(i=this.featureFlags)==null||i.updateFlags(e,s,r)}updateEarlyAccessFeatureEnrollment(e,s,r){var i;(i=this.featureFlags)==null||i.updateEarlyAccessFeatureEnrollment(e,s,r)}getEarlyAccessFeatures(e,s,r){var i;return s===void 0&&(s=!1),(i=this.featureFlags)==null?void 0:i.getEarlyAccessFeatures(e,s,r)}on(e,s){return this.dn.on(e,s)}onFeatureFlags(e){return this.featureFlags?this.featureFlags.onFeatureFlags(e):(e([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(e){return this.surveys?this.surveys.onSurveysLoaded(e):(e([],{isLoaded:!1,error:Ts}),()=>{})}onSessionId(e){var s,r;return(s=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&s!==void 0?s:()=>{}}getSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getSurveys(e,s):e([],{isLoaded:!1,error:Ts})}getActiveMatchingSurveys(e,s){s===void 0&&(s=!1),this.surveys?this.surveys.getActiveMatchingSurveys(e,s):e([],{isLoaded:!1,error:Ts})}renderSurvey(e,s){var r;(r=this.surveys)==null||r.renderSurvey(e,s)}displaySurvey(e,s){var r;s===void 0&&(s=zp),(r=this.surveys)==null||r.displaySurvey(e,s)}cancelPendingSurvey(e){var s;(s=this.surveys)==null||s.cancelPendingSurvey(e)}canRenderSurvey(e){var s,r;return(s=(r=this.surveys)==null?void 0:r.canRenderSurvey(e))!==null&&s!==void 0?s:{visible:!1,disabledReason:Ts}}canRenderSurveyAsync(e,s){var r,i;return s===void 0&&(s=!1),(r=(i=this.surveys)==null?void 0:i.canRenderSurveyAsync(e,s))!==null&&r!==void 0?r:Promise.resolve({visible:!1,disabledReason:Ts})}Jn(e){return!e||$n(e)?(C.critical("Unique user id has not been set in posthog.identify"),!1):e===vr?(C.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes(e.toLowerCase())&&!["undefined","null"].includes(e.toLowerCase())||(C.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify(e,s,r){if(!this.__loaded||!this.persistence)return C.uninitializedWarning("posthog.identify");if(he(e)&&(e=e.toString(),C.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.Jn(e)&&this.Gn("posthog.identify")){var i=this.get_distinct_id();this.register({$user_id:e}),this.get_property(Qs)||this.register_once({$had_persisted_distinct_id:!0,$device_id:i},""),e!==i&&e!==this.get_property(Ls)&&(this.unregister(Ls),this.register({distinct_id:e}));var n,o=(this.persistence.get_property(He)||Qt)===Qt,a=e!==i,l=!a&&o;if(a&&o)this.persistence.set_property(He,$t),this.setPersonPropertiesForFlags({$set:s||{},$set_once:r||{}},!1),this.capture(tn,{distinct_id:e,$anon_distinct_id:i},{$set:s||{},$set_once:r||{}}),this.Sn=pn(e,s,r),(n=this.featureFlags)==null||n.setAnonymousDistinctId(i);else if(l){this.persistence.set_property(He,$t);var u=s||{},c=r||{};this.setPersonPropertiesForFlags({$set:u,$set_once:c},!1),this.capture("$set",{$set:u,$set_once:c}),this.Sn=pn(e,s,r)}else(s||r)&&this.setPersonProperties(s,r);a?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Ut)):l&&(s||r)&&this.reloadFeatureFlags()}}setPersonProperties(e,s){if((e||s)&&this.Gn("posthog.setPersonProperties")){var r=pn(this.get_distinct_id(),e,s);this.Sn!==r?(this.setPersonPropertiesForFlags({$set:e||{},$set_once:s||{}},!0),this.capture("$set",{$set:e||{},$set_once:s||{}}),this.Sn=r):C.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}unsetPersonProperties(e){var s,r=(B(e)?e:[e]).filter(i=>W(i)&&i.length>0);r.length!==0&&this.Gn("posthog.unsetPersonProperties")&&((s=this.featureFlags)==null||s.unsetPersonPropertiesForFlags(r,!0),this.capture("$set",{$unset:r}),this.Sn=null)}group(e,s,r){if(e&&s){var i=this.getGroups(),n=i[e]!==s;if(n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:b({},i,{[e]:s})}),n||r){var o={$group_type:e,$group_key:s};r&&(o.$group_set=r),this.capture(Ga,o)}r&&this.setGroupPropertiesForFlags({[e]:r}),n&&!r&&this.reloadFeatureFlags()}else C.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),(r=this.featureFlags)==null||r.setPersonPropertiesForFlags(e,s)}resetPersonPropertiesForFlags(e){var s;e===void 0&&(e=!0),(s=this.featureFlags)==null||s.resetPersonPropertiesForFlags(e)}setGroupPropertiesForFlags(e,s){var r;s===void 0&&(s=!0),this.Gn("posthog.setGroupPropertiesForFlags")&&((r=this.featureFlags)==null||r.setGroupPropertiesForFlags(e,s))}resetGroupPropertiesForFlags(e){var s;(s=this.featureFlags)==null||s.resetGroupPropertiesForFlags(e)}reset(e){this.Yn(e)}Yn(e,s){var r,i,n,o,a,l,u,c,d,h;if(s===void 0&&(s=!1),C.info("reset"),!this.__loaded)return C.uninitializedWarning("posthog.reset");var p,f=this.get_property(Qs),g=this.get_property(Qi),v=this.get_property(zt),_=this.is_capturing();if(this.consent.reset(),s||!_||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after."),(r=this.persistence)==null||r.clear(),(i=this.sessionPersistence)==null||i.clear(),this.yn.clear(),this.Qn(),I(v)||(p=this.persistence)==null||p.register({[zt]:v}),(n=this.surveys)==null||n.reset(),(o=this.Un)==null||o.stop(),(a=this.featureFlags)==null||a.reset(),(l=this.conversations)==null||l.reset(),(u=this.logs)==null||u.reset(),(c=this.metrics)==null||c.reset(),(d=this.persistence)==null||d.set_property(He,Qt),(h=this.sessionManager)==null||h.resetSessionId(),this.Sn=null,this.config.cookieless_mode===dt)this.register_once({distinct_id:vr,$device_id:null},"");else{var w=this.config.get_device_id(ut());this.register_once({distinct_id:w,$device_id:e?w:f},""),e||I(g)||this.register({[Qi]:g})}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}shutdown(e){var s=this;return X(function*(){var r,i,n,o,a,l,u;if(s.__loaded){(r=s.Un)==null||r.stop(),(i=s.jn)==null||i.dispose(),(n=s.sessionRecording)==null||n.dispose(),(o=s.logs)==null||o.flushLogs("sendBeacon"),(a=s.metrics)==null||a.flush("sendBeacon"),(l=s.In)==null||l.unload(),(u=s.Rn)==null||u.unload();try{var c;(c=s.featureFlags)==null||c.destroy()}catch(d){C.error("Error while destroying feature flags",d)}}else C.uninitializedWarning("posthog.shutdown")})()}setIdentity(e,s){var r;this.config.identity_distinct_id=e,this.config.identity_hash=s,this.alias(e),(r=this.conversations)==null||r.Xn()}clearIdentity(){var e;delete this.config.identity_distinct_id,delete this.config.identity_hash,(e=this.conversations)==null||e.ts()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var e,s;return(e=(s=this.sessionManager)==null?void 0:s.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var s=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.sessionStartTimestamp,i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+s.sessionId);if(e!=null&&e.withTimestamp&&r){var n,o=(n=e.timestampLookBack)!==null&&n!==void 0?n:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-o,0)}return i}alias(e,s){return e===this.get_property(Qc)?(C.critical("Attempting to create alias for existing People user - aborting."),-2):this.Gn("posthog.alias")?(I(s)&&(s=this.get_distinct_id()),e!==s?(this.Kn(Ls,e),this.capture("$create_alias",{alias:e,distinct_id:s})):(C.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var s=b({},this.config);if(te(e)){var r,i,n,o,a,l,u,c,d,h,p,f;ee(this.config,Sl(e));var g=this.En();(r=this.persistence)==null||r.update_config(this.config,s,g),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new an(b({},this.config,{persistence:"sessionStorage"}),g,!1);var v=this.Cn(this.config.debug);Ge(v)&&(this.config.debug=v),Ge(this.config.debug)&&(this.config.debug?(Y.DEBUG=!0,Q.N()&&Q.F("ph_debug",!0),C.info("set_config",{config:e,oldConfig:s,newConfig:b({},this.config)})):(Y.DEBUG=!1,Q.N()&&Q.q("ph_debug"))),(i=this.featureFlags)==null||i.updateConfig==null||i.updateConfig(this.config,this.Qi()),(n=this.exceptionObserver)==null||n.onConfigChange(),(o=this.exceptions)==null||o.onConfigChange(),(a=this.sessionRecording)==null||a.startIfEnabledOrStop(),(l=this.tracingHeaders)==null||l.startIfEnabledOrStop(),(u=this.autocapture)==null||u.startIfEnabled(),(c=this.heatmaps)==null||c.startIfEnabled(),(d=this.exceptionObserver)==null||d.startIfEnabledOrStop(),(h=this.deadClicksAutocapture)==null||h.startIfEnabledOrStop(),(p=this.surveys)==null||p.loadIfEnabled(),this.es(),(f=this.externalIntegrations)==null||f.startIfEnabledOrStop()}}_overrideSDKInfo(e,s){Y.LIB_NAME=e,Y.LIB_VERSION=s}startSessionRecording(e){var s,r,i,n,o,a=e===!0,l={sampling:a||!(e==null||!e.sampling),linked_flag:a||!(e==null||!e.linked_flag),url_trigger:a||!(e==null||!e.url_trigger),event_trigger:a||!(e==null||!e.event_trigger)};Object.values(l).some(Boolean)&&((s=this.sessionManager)==null||s.checkAndGetSessionAndWindowId(),l.sampling&&((r=this.sessionRecording)==null||r.overrideSampling()),l.linked_flag&&((i=this.sessionRecording)==null||i.overrideLinkedFlag()),l.url_trigger&&((n=this.sessionRecording)==null||n.overrideTrigger("url")),l.event_trigger&&((o=this.sessionRecording)==null||o.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,s){if(this.exceptions){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(b({},i,s))}}addExceptionStep(e,s){var r;(r=this.exceptions)==null||r.addExceptionStep(e,s)}captureLog(e){var s;(s=this.logs)==null||s.captureLog(e)}get logger(){var e,s;return(e=(s=this.logs)==null?void 0:s.logger)!==null&&e!==void 0?e:Te.rs}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){var s,r;return(s=(r=this.toolbar)==null?void 0:r.loadToolbar(e))!==null&&s!==void 0&&s}get_property(e){var s;return(s=this.persistence)==null?void 0:s.props[e]}getSessionProperty(e){var s;return(s=this.sessionPersistence)==null?void 0:s.props[e]}toString(){var e,s=(e=this.config.name)!==null&&e!==void 0?e:ns;return s!==ns&&(s=ns+"."+s),s}_isIdentified(){var e,s;return((e=this.persistence)==null?void 0:e.get_property(He))===$t||((s=this.sessionPersistence)==null?void 0:s.get_property(He))===$t}Zn(){var e,s;return!(this.config.person_profiles==="never"||this.config.person_profiles===Zn&&!this._isIdentified()&>(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Ls])&&((s=this.persistence)==null||(s=s.props)==null||!s[ti]))}zn(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.Zn()||this.Gn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.Gn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}Gn(e){return this.config.person_profiles==="never"?(C.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Kn(ti,!0),!0)}En(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut();return this.config.disable_persistence||e&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==jt)}es(){var e,s,r,i,n=this.En();return((e=this.persistence)==null?void 0:e.xi)!==n&&((r=this.persistence)==null||r.set_disabled(n)),((s=this.sessionPersistence)==null?void 0:s.xi)!==n&&((i=this.sessionPersistence)==null||i.set_disabled(n)),n&&(this.yn.clear(),this.Qn()),n}opt_in_capturing(e){var s;if(this.config.cookieless_mode!==dt){if(this.gn()){var r,i,n,o,a;this.Yn(!0,!0),(r=this.sessionManager)==null||r.destroy(),(i=this.pageViewManager)==null||i.destroy(),this.sessionManager=new _l(this),this.pageViewManager=new ll(this),this.persistence&&(this.sessionPropsManager=new vl(this,this.sessionManager,this.persistence));var l,u=(n=(o=this.config.__extensionClasses)==null?void 0:o.sessionRecording)!==null&&n!==void 0?n:(a=Te.__defaultExtensionClasses)==null?void 0:a.sessionRecording;u&&(this.sessionRecording=this.pn(this.sessionRecording,new u(this)),this.hn&&((l=this.sessionRecording)==null||l.onRemoteConfig==null||l.onRemoteConfig(this.hn)))}var c,d;this.consent.optInOut(!0),this.es(),this.Bn(),(s=this.sessionRecording)==null||s.startIfEnabledOrStop(),this.config.cookieless_mode==jt&&((c=this.surveys)==null||c.loadIfEnabled()),(I(e==null?void 0:e.captureEventName)||e!=null&&e.captureEventName)&&this.capture((d=e==null?void 0:e.captureEventName)!==null&&d!==void 0?d:"$opt_in",e==null?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Hn()}else C.warn(bl)}opt_out_capturing(){var e,s,r;this.config.cookieless_mode!==dt?(this.config.cookieless_mode===jt&&this.consent.isOptedIn()&&this.Yn(!0,!0),this.consent.optInOut(!1),this.es(),this.config.cookieless_mode===jt&&(this.register({distinct_id:vr,$device_id:null}),(e=this.sessionRecording)==null||e.stopRecording(),this.sessionRecording=void 0,(s=this.sessionManager)==null||s.destroy(),(r=this.pageViewManager)==null||r.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.Hn(),this.Bn())):C.warn(bl)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var e=this.consent.consent;return e===1?"granted":e===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===dt||(this.config.cookieless_mode===jt?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.es()}_is_bot(){return ke?qu(ke,this.config.custom_blocked_useragents):void 0}Hn(){F&&(F.visibilityState==="visible"?this.wn||(this.wn=!0,this.capture(is,{title:F.title},{send_instantly:!0}),this.kn&&(F.removeEventListener(si,this.kn),this.kn=null)):this.kn||(this.kn=this.Hn.bind(this),ie(F,si,this.kn)))}debug(e){e===!1?(m==null||m.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(m==null||m.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),this.set_config({debug:!0}))}Qi(){var e=this.Mn||{};return"advanced_disable_flags"in e?!!e.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(C.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):function(s,r,i,n,o){var a=r in s&&!D(s[r]),l=i in s&&!D(s[i]);return a?s[r]:!!l&&(o&&o.warn("Config field '"+i+"' is deprecated. Please use '"+r+"' instead. The old field will be removed in a future major version."),s[i])}(e,"advanced_disable_flags","advanced_disable_decide",0,C)}Pt(e){var s;if(D(this.config.before_send))return e;var r=Object.keys((s=e.properties)!==null&&s!==void 0?s:{}).filter(lh),i=B(this.config.before_send)?this.config.before_send:[this.config.before_send],n=e;for(var o of i){if(n=o(n),D(n)){var a="Event '"+e.event+"' was rejected in beforeSend function";return ah(e.event)?C.warn(a+". This can cause unexpected behavior."):C.info(a),null}n.properties&&!gt(n.properties)||C.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}for(var l of r)if(n.properties&&D(n.properties[l]))return C.warn("Event '"+e.event+"' had its '"+l+"' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped."),null;return n}getPageViewId(){var e;return(e=this.pageViewManager.ui)==null?void 0:e.pageViewId}captureTraceFeedback(e,s){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:s})}captureTraceMetric(e,s,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:s,$ai_metric_value:String(r)})}Cn(e){var s=Ge(e)&&!e,r=Q.N()&&Q.P("ph_debug")==="true";return!s&&(!!r||e)}}Te.__defaultExtensionClasses={},Te.rs=(()=>{var t=()=>{};return{trace:t,debug:t,info:t,warn:t,error:t,fatal:t}})(),function(t,e){for(var s=0;e.length>s;s++)t.prototype[e[s]]=Yh(t.prototype[e[s]])}(Te,["identify"]);class xl{constructor(e){this.disabled=e===!1;var s=te(e)?e:{};this.thresholdPx=s.threshold_px||30,this.timeoutMs=s.timeout_ms||1e3,this.clickCount=s.click_count||3,this.clicks=[]}isRageClick(e,s,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(s-i.y)r-i.timestamp){if(this.clicks.push({x:e,y:s,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:s,timestamp:r}];return!1}}var mn="$copy_autocapture",vn=se("[AutoCapture]");function _n(t,e){return e.length>t?e.slice(0,t)+"...":e}function ef(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Ct(e));return e}function tf(t,e){var s,r,i=e.e,n=e.maskAllElementAttributes,o=e.maskAllText,a=e.elementAttributeIgnoreList,l=e.elementsChainAsString,u=e.disableCaptureUrlHashes;if(!Ct(t))return{props:{}};for(var c=[t],d=new Set([t]),h=t;h.parentNode&&!Me(h,"body")&&gu>c.length;)if(fu(h.parentNode)){var p=h.parentNode.host;if(d.has(p))break;d.add(p),c.push(p),h=p}else{if(!Ct(h.parentNode)||d.has(h.parentNode))break;d.add(h.parentNode),c.push(h.parentNode),h=h.parentNode}var f,g,v=[],_={},w=!1,S=!1;if(Z(c,E=>{var A=eo(E);if(Me(E,"a")){var $=E.getAttribute("href");w=!!(A&&$&&Vs($))&&(u?It($):$)}L(ni(E),"ph-no-capture")&&(S=!0),v.push(function(T,O,J,z,H){H===void 0&&(H=!1);var oe=T.tagName.toLowerCase(),pe={tag_name:oe};Ho.indexOf(oe)>-1&&!J&&(pe.$el_text=oe.toLowerCase()==="a"||oe.toLowerCase()==="button"?_n(1024,nl(T)):_n(1024,er(T)));var Ie=ni(T);Ie.length>0&&(pe.classes=Ie.filter(function(ae){return ae!==""})),Z(T.attributes,function(ae){var me;if((!wu(T)||["name","id","class","aria-label"].indexOf(ae.name)!==-1)&&(z==null||!z.includes(ae.name))&&!O&&Vs(ae.value)&&(!W(me=ae.name)||me.substring(0,10)!=="_ngcontent"&&me.substring(0,7)!=="_nghost")){var ge=ae.value;ae.name==="class"&&(ge=Uo(ge).join(" ")),pe["attr__"+ae.name]=_n(1024,ae.name==="href"&&H?It(ge):ge)}});for(var _e=1,Ce=1,Re=T;Re=ef(Re);)_e++,Re.tagName===T.tagName&&Ce++;return pe.nth_child=_e,pe.nth_of_type=Ce,pe}(E,n,o,a,u));var N=function(T){if(!eo(T))return{};var O={};return Z(T.attributes,function(J){if(J.name&&J.name.indexOf("data-ph-capture-attribute")===0){var z=J.name.replace("data-ph-capture-attribute-",""),H=J.value;z&&H&&Vs(H)&&(O[z]=H)}}),O}(E);ee(_,N)}),S)return{props:{},explicitNoCapture:S};if(o||(v[0].$el_text=Me(t,"a")||Me(t,"button")?nl(t):er(t)),w){var k,x;v[0].attr__href=w;var P=(k=oi(w))==null?void 0:k.host,M=m==null||(x=m.location)==null?void 0:x.host;P&&M&&P!==M&&(f=w)}return{props:ee({$event_type:i.type,$ce_version:1},l?{}:{$elements:v},{$elements_chain:(g=v,function(E){return E.map(A=>{var $,N,T="";if(A.tag_name&&(T+=A.tag_name),A.attr_class)for(var O of(A.attr_class.sort(),A.attr_class))T+="."+O.replace(/"/g,"");var J=b({},A.text?{text:A.text}:{},{"nth-child":($=A.nth_child)!==null&&$!==void 0?$:0,"nth-of-type":(N=A.nth_of_type)!==null&&N!==void 0?N:0},A.href?{href:A.href}:{},A.attr_id?{attr_id:A.attr_id}:{},A.attributes),z={};return Nr(J).sort((H,oe)=>H[0].localeCompare(oe[0])).forEach(H=>{var oe=H[1];return z[ol(H[0].toString())]=ol(oe.toString())}),(T+=":")+Nr(z).map(H=>H[0]+'="'+H[1]+'"').join("")}).join(";")}(function(E){return E.map(A=>{var $,N,T={text:($=A.$el_text)==null?void 0:$.slice(0,400),tag_name:A.tag_name,href:(N=A.attr__href)==null?void 0:N.slice(0,2048),attr_class:gp(A),attr_id:A.attr__id,nth_child:A.nth_child,nth_of_type:A.nth_of_type,attributes:{}};return Nr(A).filter(O=>O[0].indexOf("attr__")===0).forEach(O=>T.attributes[O[0]]=O[1]),T})}(g)))},(s=v[0])!=null&&s.$el_text?{$el_text:(r=v[0])==null?void 0:r.$el_text}:{},f&&i.type==="click"?{$external_click_url:f}:{},_)}}var Ns=se("[ExceptionAutocapture]"),kl=()=>{},sf=se("[TracingHeaders]"),Nt=se("[Web Vitals]"),Il=9e5,Cl="disabled",Fl="lazy_loading",Ms="awaiting_config",xr="missing_config";se("[SessionRecording]"),se("[SessionRecording]");var lo="[SessionRecording]",ot=se(lo),rf=se("[Heatmaps]");function yn(t){return te(t)&&"clientX"in t&&"clientY"in t&&he(t.clientX)&&he(t.clientY)}var kr=se("[Product Tours]"),wn=t=>{var e;return!t.config.disable_product_tours&&!((e=t.persistence)==null||!e.get_property(Lo))},nf=["$set_once","$set"],Ye=se("[SiteApps]"),Pl="Error while initializing PostHog app with config id ";function ss(t,e,s){if(D(t))return!1;switch(s){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch{return!1}default:return!1}}class of{constructor(e){this.ns=new Vo,this.ss=(s,r)=>this.os(s,r)&&this.ls(s,r)&&this.us(s,r)&&this.hs(s,r),this.os=(s,r)=>r==null||!r.event||(s==null?void 0:s.event)===(r==null?void 0:r.event),this._instance=e,this.ds=new Set,this.vs=new Set}init(){var e,s;I((e=this._instance)==null?void 0:e._addCaptureHook)||(s=this._instance)==null||s._addCaptureHook((r,i)=>{this.on(r,i)})}register(e){var s,r;if(!I((s=this._instance)==null?void 0:s._addCaptureHook)&&(e.forEach(o=>{var a,l;(a=this.vs)==null||a.add(o),(l=o.steps)==null||l.forEach(u=>{var c;(c=this.ds)==null||c.add((u==null?void 0:u.event)||"")})}),(r=this._instance)!=null&&r.autocapture)){var i,n=new Set;e.forEach(o=>{var a;(a=o.steps)==null||a.forEach(l=>{l!=null&&l.selector&&n.add(l==null?void 0:l.selector)})}),(i=this._instance)==null||i.autocapture.setElementSelectors(n)}}on(e,s){var r;s!=null&&e.length!=0&&(this.ds.has(e)||this.ds.has(s.event))&&this.vs&&((r=this.vs)==null?void 0:r.size)>0&&this.vs.forEach(i=>{this.cs(s,i)&&this.ns.emit("actionCaptured",i.name)})}fs(e){this.onAction("actionCaptured",s=>e(s))}cs(e,s){if((s==null?void 0:s.steps)==null)return!1;for(var r of s.steps)if(this.ss(e,r))return!0;return!1}onAction(e,s){return this.ns.on(e,s)}ls(e,s){if(s!=null&&s.url){var r,i=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!ss(i,s.url,s.url_matching||"contains"))return!1}return!0}us(e,s){return!!this.ps(e,s)&&!!this.gs(e,s)&&!!this.ys(e,s)}ps(e,s){var r;if(s==null||!s.href)return!0;var i=this.bs(e);if(i.length>0)return i.some(a=>ss(a.href,s.href,s.href_matching||"exact"));var n,o=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!o&&ss((n=o.match(/(?::|")href="(.*?)"/))?n[1]:"",s.href,s.href_matching||"exact")}gs(e,s){var r;if(s==null||!s.text)return!0;var i=this.bs(e);if(i.length>0)return i.some(u=>ss(u.text,s.text,s.text_matching||"exact")||ss(u.$el_text,s.text,s.text_matching||"exact"));var n,o,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(n=function(u){for(var c,d=[],h=/(?::|")text="(.*?)"/g;!D(c=h.exec(u));)d.includes(c[1])||d.push(c[1]);return d}(l),o=s.text,a=s.text_matching||"exact",n.some(u=>ss(u,o,a)))}ys(e,s){var r,i;if(s==null||!s.selector)return!0;var n=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(n!=null&&n.includes(s.selector))return!0;var o=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(s.selector_regex&&o)try{return new RegExp(s.selector_regex).test(o)}catch{return!1}return!1}bs(e){var s;return(e==null||(s=e.properties)==null?void 0:s.$elements)==null?[]:e==null?void 0:e.properties.$elements}hs(e,s){return s==null||!s.properties||s.properties.length===0||Ku(s.properties.reduce((r,i)=>{var n=B(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:n,operator:i.operator||"exact"},r},{}),e==null?void 0:e.properties)}}class af{constructor(e){var s;this._s=[],this._instance=e,this.ws=new Map,this.ks=new Map,this.xs=new Map,(s=this._instance)==null||s.onSessionId==null||s.onSessionId(r=>this.Ss(r))}Cs(e){return!1}Ms(){return null}Ts(e){}Es(){}Is(e,s){return!!e&&Ku(e.propertyFilters,s==null?void 0:s.properties)}Ps(e,s){var r=new Map;return e.forEach(i=>{var n;(n=i.conditions)==null||(n=n[s])==null||(n=n.values)==null||n.forEach(o=>{if(o!=null&&o.name){var a=r.get(o.name)||[];a.push(i.id),r.set(o.name,a)}})}),r}Rs(e,s,r){var i=(r===Ps.Activation?this.ws:this.ks).get(e),n=[];return this.As(o=>{n=o.filter(a=>i==null?void 0:i.includes(a.id))}),n.filter(o=>{var a,l=(a=o.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find(u=>u.name===e);return this.Is(l,s)})}register(e){var s;I((s=this._instance)==null?void 0:s._addCaptureHook)||(this.Fs(e),this.Ls(e))}Ls(e){var s=e.filter(r=>{var i,n;return((i=r.conditions)==null?void 0:i.actions)&&((n=r.conditions)==null||(n=n.actions)==null||(n=n.values)==null?void 0:n.length)>0});s.length!==0&&(this.Os==null&&(this.Os=new of(this._instance),this.Os.init(),this.Os.fs(r=>{this.onAction(r)})),s.forEach(r=>{var i,n,o,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(n=r.conditions)!=null&&(n=n.actions)!=null&&n.values&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0&&((a=this.Os)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach(u=>{if(u&&u.name){var c=this.xs.get(u.name);c&&c.push(r.id),this.xs.set(u.name,c||[r.id])}}))}))}Fs(e){var s,r=e.filter(n=>{var o,a;return((o=n.conditions)==null?void 0:o.events)&&((a=n.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0}),i=e.filter(n=>{var o,a;return((o=n.conditions)==null?void 0:o.cancelEvents)&&((a=n.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0});r.length===0&&i.length===0||((s=this._instance)==null||s._addCaptureHook((n,o)=>{this.onEvent(n,o)}),this.ws=this.Ps(e,Ps.Activation),this.ks=this.Ps(e,Ps.Cancellation))}onEvent(e,s){var r,i,n=this.Ds(),o=(s==null||(r=s.properties)==null?void 0:r.$survey_id)||(s==null||(i=s.properties)==null?void 0:i.$product_tour_id);if(o&&this.getActivatedIds().includes(o)){var a=this.$s(e,o);if(a==="consume")return n.info("event consumed activated item, removing it",{event:e,itemId:o}),void this.Ns([o]);if(a==="persist")return n.info("shown item promoted to persisted activation",{event:e,itemId:o}),this.qs(o),void this.js([o])}if(this.ks.has(e)){var l=this.Rs(e,s,Ps.Cancellation);l.length>0&&(n.info("cancel event matched, cancelling items",{event:e,itemsToCancel:l.map(c=>c.id)}),this.Ns(l.map(c=>c.id)),l.forEach(c=>this.Bs(c.id)))}if(this.ws.has(e)){n.info("event name matched",{event:e,eventPayload:s,items:this.ws.get(e)});var u=this.Rs(e,s,Ps.Activation);this.Hs(u.map(c=>c.id))}}onAction(e){this.xs.has(e)&&this.Hs(this.xs.get(e)||[])}Hs(e){var s;if(e.length!==0){var r=!((s=this._instance)==null||s.get_session_id==null||!s.get_session_id()),i=[];for(var n of e)r&&this.Cs(n)?this.qs(n)&&this.Us(n):i.push(n);i.length>0&&(this._s=[...new Set([...this._s,...i])]),this.Ds().info("updating activated items",{activatedItems:this.getActivatedIds()})}}qs(e){this._s=this._s.filter(r=>r!==e);var s=this.zs();return!s.includes(e)&&(this.Ws([...s,e]),this.Vs(),!0)}Ns(e){var s=new Set(e);this._s=this._s.filter(n=>!s.has(n));var r=this.Zs(),i=r.filter(n=>!s.has(n));i.length!==r.length&&(this.Ws(i),i.length===0&&this.Gs()),this.js(e)}Qs(){var e,s=this.Ms();if(!s)return{};var r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s];return r&&typeof r=="object"?r:{}}Us(e){if(this.Ms()){var s=this.Qs();this.Ts(b({},s,{[e]:Date.now()}))}}js(e){if(this.Ms()){var s=this.Qs(),r={},i=!1;for(var n of Object.entries(s)){var o=n[0],a=n[1];e.includes(o)?i=!0:r[o]=a}i&&(gt(r)?this.Es():this.Ts(r))}}Ks(){this.Ms()&&this.Es()}getActivationTimestamp(e){if(this.zs().includes(e)){var s=this.Qs()[e];return he(s)?s:void 0}}Zs(){var e,s=this.Js();return((e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[s])||[]}zs(){var e,s,r=this.Zs();if(r.length===0)return[];var i=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[this.Ys()],n=(s=this._instance)==null||s.get_session_id==null?void 0:s.get_session_id();return n&&i===n?r:[]}Vs(){var e,s=(e=this._instance)==null||e.get_session_id==null?void 0:e.get_session_id();s&&this.Xs(s)}Gs(){this.ta()}Ss(e){var s,r=(s=this._instance)==null||(s=s.persistence)==null?void 0:s.props[this.Ys()];if(r&&r!==e){var i=this.Zs(),n=this.Qs();i.length>0&&(this.Ws([]),i.filter(o=>he(n[o])).forEach(o=>this.Bs(o))),this.Gs(),this.Ks()}}getActivatedIds(){return[...new Set([...this.zs(),...this._s])].filter(e=>!this.ea(e))}reset(){this._s=[],this.Zs().length>0&&this.Ws([]),this.Gs(),this.Ks()}getEventToItemsMap(){return this.ws}ia(){return this.Os}}class lf extends af{constructor(e){super(e)}Js(){return Vn}Ys(){return $r}Ms(){return Rr}Ts(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Rr]:e})}Es(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister(Rr)}Cs(e){var s,r;this.As(n=>{r=n.find(o=>o.id===e)});var i=(s=r)==null||(s=s.appearance)==null?void 0:s.surveyPopupDelaySeconds;return he(i)&&i>0}ra(){return pt.SHOWN}As(e){var s;(s=this._instance)==null||s.getSurveys(e)}Bs(e){var s;(s=this._instance)==null||s.cancelPendingSurvey(e)}Ds(){return V}Ws(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[Vn]:e})}Xs(e){var s;(s=this._instance)==null||(s=s.persistence)==null||s.register({[$r]:e})}ta(){var e;(e=this._instance)==null||(e=e.persistence)==null||e.unregister($r)}ea(){return!1}$s(e,s){var r;this.As(n=>{r=n.find(o=>o.id===s)});var i=!r||function(n){var o;return Ju(n)&&!((o=n.conditions)==null||(o=o.events)==null||!o.repeatedActivation)||n.schedule==="always"}(r);return i?e===pt.SHOWN?"consume":"ignore":e===pt.SHOWN?"persist":e===pt.DISMISSED||e===pt.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Ir="SDK is not enabled or survey functionality is not yet loaded",Al="Disabled. Not loading surveys.",cf=m!=null&&m.location?ai(m.location.hash,"__posthog")||ai(location.hash,"state"):null,$l="_postHogToolbarParams",Rl=se("[Toolbar]"),Tl=se("[FeatureFlags]");class uf{constructor(e,s){s===void 0&&(s=!1),this.na=!1,this.update(e,s)}update(e,s){this.sa=((r,i)=>{var n,o,a,l;return{bootstrap:{featureFlags:(n=r.bootstrap)==null?void 0:n.featureFlags,featureFlagPayloads:(o=r.bootstrap)==null?void 0:o.featureFlagPayloads},remoteRequestsDisabled:i,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,requestTimeoutMs:r.feature_flag_request_timeout_ms,compression:r.disable_compression?"none":"base64",evaluationContexts:(a=(l=r.evaluation_contexts)!==null&&l!==void 0?l:r.evaluation_environments)!==null&&a!==void 0?a:[],flagKeys:B(r.flag_keys)?r.flag_keys:void 0}})(e,s),!e.evaluation_environments||e.evaluation_contexts||this.na||(Tl.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.na=!0),I(e.flag_keys)||B(e.flag_keys)||Tl.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.sa}}var Nl=se("[FeatureFlags]"),Mt=se("[FeatureFlags]",{debugEnabled:!0}),bn=`" failed. Feature flags didn't load in time.`,Ml="connection_error",Ol=t=>{for(var e={},s=0;t.length>s;s++)e[t[s]]=!0;return e},Ll=t=>{var e={};for(var s of Nr(t||{})){var r=s[1];r&&(e[s[0]]=r)}return e},Ze=se("[Error tracking]"),Bl="Refusing to render web experiment since the viewer is a likely bot",df={icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>e.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>ui(e,t),not_regex:(t,e)=>!ui(e,t),exact:(t,e)=>e===t,is_not:(t,e)=>e!==t};class ye{get Ne(){return this._instance.config}constructor(e){var s=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),s.getWebExperiments(i=>{ye.aa("retrieved web experiments from the server"),s.oa=new Map,i.forEach(n=>{if(n.feature_flag_key){var o;s.oa&&(ye.aa("setting flag key ",n.feature_flag_key," to web experiment ",n),(o=s.oa)==null||o.set(n.feature_flag_key,n));var a=s._instance.getFeatureFlag(n.feature_flag_key);W(a)&&n.variants[a]&&s.la(n.name,a,n.variants[a].transforms)}else if(n.variants)for(var l in n.variants){var u=n.variants[l];ye.ua(u,s._instance)&&s.la(n.name,l,u.transforms)}})},r)},this._instance=e,this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}initialize(){}onFeatureFlags(e){if(this._is_bot())ye.aa(Bl);else if(!this.Ne.disable_web_experiments){if(D(this.oa))return this.oa=new Map,this.loadIfEnabled(),void this.previewWebExperiment();ye.aa("applying feature flags",e),e.forEach(s=>{var r;if(this.oa&&(r=this.oa)!=null&&r.has(s)){var i,n=this._instance.getFeatureFlag(s),o=(i=this.oa)==null?void 0:i.get(s);n&&o!=null&&o.variants[n]&&this.la(o.name,n,o.variants[n].transforms)}})}}previewWebExperiment(){var e=ye.getWindowLocation();if(e!=null&&e.search){var s=ms(e==null?void 0:e.search,"__experiment_id"),r=ms(e==null?void 0:e.search,"__experiment_variant");s&&r&&(ye.aa("previewing web experiments "+s+" && "+r),this.getWebExperiments(i=>{this.ha(parseInt(s),r,i)},!1,!0))}}loadIfEnabled(){this.Ne.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,s,r){if(this.Ne.disable_web_experiments&&!r)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!s)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Ne.token),method:"GET",timestampMode:"query",callback:n=>e(n.statusCode===200&&n.json&&n.json.experiments||[])})}ha(e,s,r){var i=r.filter(n=>n.id===e);i&&i.length>0&&(ye.aa("Previewing web experiment ["+i[0].name+"] with variant ["+s+"]"),this.la(i[0].name,s,i[0].variants[s].transforms))}static ua(e,s){return!D(e.conditions)&&ye.da(e,s)&&ye.va(e)}static da(e,s){var r;if(D(e.conditions)||D((r=e.conditions)==null?void 0:r.url))return!0;var i=ye.getWindowLocation();if(i){var n,o,a,l=du(s,i.href);return(n=e.conditions)==null||!n.url||df[(o=(a=e.conditions)==null?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](e.conditions.url,l)}return!1}static getWindowLocation(){return m==null?void 0:m.location}static va(e){var s;if(D(e.conditions)||D((s=e.conditions)==null?void 0:s.utm))return!0;var r=Iu();if(r.utm_source){var i,n,o,a,l,u,c,d,h=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((n=e.conditions)==null||(n=n.utm)==null?void 0:n.utm_campaign)==r.utm_campaign,p=(o=e.conditions)==null||(o=o.utm)==null||!o.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,f=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((u=e.conditions)==null||(u=u.utm)==null?void 0:u.utm_medium)==r.utm_medium,g=(c=e.conditions)==null||(c=c.utm)==null||!c.utm_term||((d=e.conditions)==null||(d=d.utm)==null?void 0:d.utm_term)==r.utm_term;return h&&f&&g&&p}return!1}static aa(e){for(var s=arguments.length,r=new Array(s>1?s-1:0),i=1;s>i;i++)r[i-1]=arguments[i];C.info("[WebExperiments] "+e,r)}la(e,s,r){this._is_bot()?ye.aa(Bl):s!=="control"?r.forEach(i=>{if(i.selector){var n;ye.aa("applying transform of variant "+s+" for experiment "+e+" ",i);var o=(n=document)==null?void 0:n.querySelectorAll(i.selector);o==null||o.forEach(a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)})}}):ye.aa("Control variants leave the page unmodified.")}_is_bot(){return ke&&this._instance?qu(ke,this.Ne.custom_blocked_useragents):void 0}}var Ue=se("[Conversations]"),Ot="Conversations not available yet.",Dl="console",ed="__posthogHandledLogsRequestError",En=(t,e)=>{var s=t instanceof Error?t:new Error(e);return s[ed]=!0,s},jl=t=>!!t&&typeof t=="object"&&t[ed]===!0,Pi={featureFlags:class{constructor(t){this.name="featureFlags",this.ca=!1,this.featureFlagEventHandlers=[],this.rt=Nl,this.fa={},this.pa={},this.ga=[],this.ma=!1,this.ya=!1,this.ba=0,this._a=!1,this.wa=!1,this.ka=!1,this.xa=!1,this.Sa=0,this.Ca=()=>{var e=this.Ma();this.Sa=0,e&&this.reloadFeatureFlags()},"get"in t?this.Ta=t:(this.Ea=new uf(t.config,t.Qi()),this.Ta=this.Ea)}updateConfig(t,e){var s;(s=this.Ea)==null||s.update(t,e)}setup(t){return this.Ia=t,this.rt=t.logger.createLogger("[FeatureFlags]"),s=()=>{this.Ia===t&&(this.Ia=void 0,this.nn=t,this.Pa(t))},(e=t.kv.initialize())!=null&&e.then?e.then(s):s();var e,s}Pa(t){if(this.nn===t)return m&&ie(m,"online",this.Ca),this.Ra=t.registerDynamicEventProperties(()=>this.Aa()?this.fa:this.pa),this.Fa(),this.initialize()}destroy(){m==null||m.removeEventListener("online",this.Ca)}dispose(){var t;this.ba++,this.wa=!1,this.Ia=void 0,this.nn&&(this.La(),(t=this.Ra)==null||t.dispose(),this.Ra=void 0,this.ga=[],m==null||m.removeEventListener("online",this.Ca),this.nn=void 0)}get Ne(){return this.Ta.get()}Oa(t){var e;return(e=this.nn)==null?void 0:e.kv.get(t)}F(t){this.Da(()=>{var e;return(e=this.nn)==null?void 0:e.kv.set(t)})}q(t){this.Da(()=>{var e;return(e=this.nn)==null?void 0:e.kv.remove(t)})}Da(t){try{t()}catch(e){this.rt.error("Failed to update feature flag persistence",e)}}Fa(){var t={};for(var e of[Ds,js,Ar,Qe]){var s=this.Oa(e);I(s)||(t[e]=s)}this.fa=t;var r=b({},t),i=this.Oa(Lt);if(i)for(var n of Object.entries(i))r["$feature/"+n[0]]=n[1];this.pa=r}Aa(){var t=this.Ne.cacheTtlMs;if(!t||0>=t)return!1;var e=this.Oa(qs);return typeof e!="number"||Date.now()-e>t}$a(){return!!this.Aa()&&(this.xa||this.ya||(this.xa=!0,this.rt.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Na(){var t=this.Ne.evaluationContexts;return t!=null&&t.length?t.filter(e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid evaluation context found:",e,"Expected non-empty string"),s}):[]}qa(){var t=this.Ne.flagKeys;if(!I(t))return t.filter(e=>{var s=e&&typeof e=="string"&&e.trim().length>0;return s||this.rt.error("Invalid flag key found:",e,"Expected non-empty string"),s})}initialize(){var t,e,s=this.Ne,r=(t=(e=s.bootstrap)==null?void 0:e.featureFlags)!==null&&t!==void 0?t:{};if(Object.keys(r).length){var i,n,o=(i=(n=s.bootstrap)==null?void 0:n.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(r).filter(u=>!!r[u]).reduce((u,c)=>(u[c]=r[c]||!1,u),{}),l=Object.keys(o).filter(u=>a[u]).reduce((u,c)=>(o[c]&&(u[c]=o[c]),u),{});return this.ja({featureFlags:a,featureFlagPayloads:l})}}updateFlags(t,e,s){var r,i,n=s!=null&&s.merge&&(r=this.Oa(Lt))!==null&&r!==void 0?r:{},o=s!=null&&s.merge&&(i=this.Oa(js))!==null&&i!==void 0?i:{},a=b({},n,t),l=b({},o,e),u={};for(var c of Object.entries(a)){var d=c[0],h=c[1];u[d]={key:d,enabled:Ra(h),variant:Ta(h),reason:void 0,metadata:I(l==null?void 0:l[d])?void 0:{id:0,version:void 0,description:void 0,payload:l[d]}}}this.ja({flags:u})}get hasLoadedFlags(){return this.ma}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var t=this.Oa(zn),e=this.Oa(Qe),s=this.Oa(Bt);if(!s&&!e)return t||{};var r=ee({},t||{}),i=[...new Set([...Object.keys(s||{}),...Object.keys(e||{})])];for(var n of i){var o,a,l=r[n],u=e==null?void 0:e[n],c=I(u)?(o=l==null?void 0:l.enabled)!==null&&o!==void 0&&o:!!u,d=I(u)?l==null?void 0:l.variant:typeof u=="string"?u:void 0,h=s==null?void 0:s[n],p=b({},l,{enabled:c,variant:c?d??(l==null?void 0:l.variant):void 0});c!==(l==null?void 0:l.enabled)&&(p.original_enabled=l==null?void 0:l.enabled),d!==(l==null?void 0:l.variant)&&(p.original_variant=l==null?void 0:l.variant),h&&(p.metadata=b({},l==null?void 0:l.metadata,{payload:h,original_payload:l==null||(a=l.metadata)==null?void 0:a.payload})),r[n]=p}return this.ca||(this.rt.warn(" Overriding feature flag details!",{flagDetails:t,overriddenPayloads:s,finalDetails:r}),this.ca=!0),r}getAllFeatureFlags(){var t=this.getFlagVariants(),e=this.getFlagPayloads();return Object.keys(t).map(s=>{var r=t[s];return{key:s,enabled:Ra(r),variant:Ta(r),payload:$a(e[s])}})}getFlagVariants(){var t=this.Oa(Lt),e=this.Oa(Qe);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)s[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flags!",{enabledFlags:t,overriddenFlags:e,finalFlags:s}),this.ca=!0),s}getFlagPayloads(){var t=this.Oa(js),e=this.Oa(Bt);if(!e)return t||{};for(var s=ee({},t||{}),r=Object.keys(e),i=0;r.length>i;i++)s[r[i]]=e[r[i]];return this.ca||(this.rt.warn(" Overriding feature flag payloads!",{flagPayloads:t,overriddenPayloads:e,finalPayloads:s}),this.ca=!0),s}reloadFeatureFlags(){this._a||this.Ne.featureFlagsDisabled||this.Ma()||this.Ba||(this.ga.slice().forEach(t=>{try{t()}catch(e){this.rt.error("Error while running feature flags reloading callback",e)}}),this.Ba=setTimeout(()=>{this.Ha()},5))}La(){clearTimeout(this.Ba),this.Ba=void 0}onReloading(t){return this.ga.push(t),()=>{this.ga=this.ga.filter(e=>e!==t)}}ensureFlagsLoaded(){this.ma||this.ya||this.Ba||this.reloadFeatureFlags()}setAnonymousDistinctId(t){this.$anon_distinct_id=t}setReloadingPaused(t){this._a=t}resetFlagCallReported(){this.q(Ut)}Ha(t){this.La();var e=this.nn;if(e&&!this.Ne.remoteRequestsDisabled&&!this.Ma())if(this.ya)this.wa=!0;else{var s={token:e.projectToken,distinct_id:e.distinctId,groups:e.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b({},e.initialPersonProperties,this.Oa(lt)||{},{$lib:e.library.name,$lib_version:e.library.version}),group_properties:this.Oa(Dt),timezone:Ru()};I(e.deviceId)||(s.$device_id=e.deviceId),(t!=null&&t.disableFlags||this.Ne.featureFlagsDisabled)&&(s.disable_flags=!0);var r=this.Na();r.length&&(s.evaluation_contexts=r);var i=this.qa();I(i)||(s.flag_keys=i);var n=this.Ne.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(n?"&only_evaluate_survey_feature_flags=true":""),a=this.ba;this.ya=!0;var l=()=>{this.wa&&(this.wa=!1,this.Ha())},u=c=>{this.ya=!1,a===this.ba&&(this.F({[Tr]:[Ml]}),this.rt.error("Feature flag request failed",c)),l()};try{e.sendRequest(o,{target:"flags",method:"POST",body:s,compression:this.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:this.Ne.requestTimeoutMs}).then(c=>{var d,h,p=(d=c.json)!==null&&d!==void 0?d:{},f=c.statusCode!==200;if(this.ya=!1,a===this.ba){if(this.Ua(c.statusCode),f||this.wa||(this.$anon_distinct_id=void 0),!s.disable_flags||this.wa){this.ka=!f;var g=[];c.error?g.push(c.error instanceof Error&&c.error.name==="AbortError"?"timeout":c.error instanceof Error?Ml:"unknown_error"):c.statusCode!==200&&g.push("api_error_"+c.statusCode),p.errorsWhileComputingFlags&&g.push("errors_while_computing_flags");var v=!((h=p.quotaLimited)==null||!h.includes("feature_flags"));v&&g.push("quota_limited"),this.F({[Tr]:g}),v?this.rt.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):s.disable_flags||this.ja(p,f,{partialResponse:n}),l()}}else l()}).catch(u)}catch(c){u(c)}}}Ma(){return xu(this.Sa,3)}Ua(t){this.Sa=ku(t,this.Sa,3,()=>this.rt.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(t,e){var s;if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var r=this.getFeatureFlagResult(t,e);return(s=r==null?void 0:r.variant)!==null&&s!==void 0?s:r==null?void 0:r.enabled}}else this.rt.warn('getFeatureFlag for key "'+t+bn)}getFeatureFlagDetails(t){return this.getFlagsWithDetails()[t]}getFeatureFlagPayload(t){var e=this.getFeatureFlagResult(t,{send_event:!1});return e==null?void 0:e.payload}getFeatureFlagResult(t,e){if(e===void 0&&(e={}),!e.fresh||this.ka)if(this.ma||this.getFlags()&&this.getFlags().length>0){if(!this.$a()){var s,r=this.getFlagVariants(),i=t in r,n=r[t],o=this.getFlagPayloads()[t],a=String(n),l=this.Oa(Ar)||void 0,u=this.Oa(qs)||void 0,c=this.Oa(Ut)||{};if(this.Ne.deduplicateCallsPerSession){var d,h=(d=this.nn)==null?void 0:d.session.sessionId,p=this.Oa(Hs);h&&h!==p&&(c={},s=h)}if(e.send_event||!("send_event"in e))if(t in c&&c[t].includes(a))s&&this.F({[Ut]:c,[Hs]:s});else{var f,g,v,_,w,S,k,x,P,M;B(c[t])?c[t].push(a):c[t]=[a],this.F(b({[Ut]:c},s?{[Hs]:s}:{}));var E=this.getFeatureFlagDetails(t),A=[...(f=this.Oa(Tr))!==null&&f!==void 0?f:[]];I(n)&&A.push("flag_missing");var $={$feature_flag:t,$feature_flag_response:n,$feature_flag_payload:o||null,$feature_flag_request_id:l,$feature_flag_evaluated_at:u,$feature_flag_bootstrapped_response:((g=this.Ne.bootstrap)==null||(g=g.featureFlags)==null?void 0:g[t])||null,$feature_flag_bootstrapped_payload:((v=this.Ne.bootstrap)==null||(v=v.featureFlagPayloads)==null?void 0:v[t])||null,$used_bootstrap_value:!this.ka};I(E==null||(_=E.metadata)==null?void 0:_.has_experiment)||($.$feature_flag_has_experiment=E.metadata.has_experiment),I(E==null||(w=E.metadata)==null?void 0:w.version)||($.$feature_flag_version=E.metadata.version);var N,T=(S=E==null||(k=E.reason)==null?void 0:k.description)!==null&&S!==void 0?S:E==null||(x=E.reason)==null?void 0:x.code;T&&($.$feature_flag_reason=T),E!=null&&(P=E.metadata)!=null&&P.id&&($.$feature_flag_id=E.metadata.id),I(E==null?void 0:E.original_variant)&&I(E==null?void 0:E.original_enabled)||($.$feature_flag_original_response=I(E.original_variant)?E.original_enabled:E.original_variant),E!=null&&(M=E.metadata)!=null&&M.original_payload&&($.$feature_flag_original_payload=E==null||(N=E.metadata)==null?void 0:N.original_payload),A.length&&($.$feature_flag_error=A.join(",")),this.za($)}else s&&this.F({[Ut]:c,[Hs]:s});if(i)return{key:t,enabled:!!n,variant:typeof n=="string"?n:void 0,payload:$a(o)}}}else this.rt.warn('getFeatureFlagResult for key "'+t+bn)}za(t){try{var e;(e=this.nn)==null||e.capture("$feature_flag_called",t).catch(s=>{this.rt.error("Failed to capture feature flag call",s)})}catch(s){this.rt.error("Failed to capture feature flag call",s)}}getRemoteConfigPayload(t,e){this.Wa(t,e)}Wa(t,e){var s=this;return X(function*(){var r=s.nn;if(r){var i={distinct_id:r.distinctId,token:r.projectToken,person_properties:{$lib:r.library.name,$lib_version:r.library.version}},n=s.Na();n.length&&(i.evaluation_contexts=n);var o,a=s.qa();I(a)||(i.flag_keys=a);try{var l,u=(l=(yield r.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:s.Ne.compression==="base64"?xe.Base64:void 0,sentAt:"body",timeoutMs:s.Ne.requestTimeoutMs})).json)==null?void 0:l.featureFlagPayloads;o=(u==null?void 0:u[t])||void 0}catch(c){return void s.rt.error("Remote config feature flag request failed",c)}try{e(o)}catch(c){s.rt.error("Remote config feature flag callback failed",c)}}})()}isFeatureEnabled(t,e){if(e===void 0&&(e={}),e.fresh&&!this.ka)return e.defaultValue;if(!(this.ma||this.getFlags()&&this.getFlags().length>0))return this.rt.warn('isFeatureEnabled for key "'+t+bn),e.defaultValue;var s=this.getFeatureFlag(t,e);return I(s)?e.defaultValue:!!s}addFeatureFlagsHandler(t){this.featureFlagEventHandlers.push(t)}removeFeatureFlagsHandler(t){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(e=>e!==t)}receivedFeatureFlags(t,e,s){this.ja(t,e,s)}ja(t,e,s){if(this.nn){this.ma=!0;var r=function(i,n,o,a,l,u){n===void 0&&(n={}),o===void 0&&(o={}),a===void 0&&(a={}),u===void 0&&(u=Nl);var c=((P,M)=>{var E=P.flags;return E?b({},P,{featureFlags:Object.fromEntries(Object.keys(E).map(A=>{var $;return[A,($=E[A].variant)!==null&&$!==void 0?$:E[A].enabled]})),featureFlagPayloads:Object.fromEntries(Object.keys(E).filter(A=>E[A].enabled).filter(A=>{var $;return($=E[A].metadata)==null?void 0:$.payload}).map(A=>{var $;return[A,($=E[A].metadata)==null?void 0:$.payload]}))}):(P.featureFlags&&M.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),P)})(i,u),d=c.flags,h=c.featureFlags,p=c.featureFlagPayloads;if(h){var f=i.requestId,g=i.evaluatedAt;if(B(h)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var v={};if(h)for(var _=0;h.length>_;_++)v[h[_]]=!0;return{[Ds]:h,[Lt]:v,[Xr]:!1}}var w=h,S=p,k=d;if(l!=null&&l.partialResponse)w=b({},n,w),S=b({},o,S),k=b({},a,k);else if(i.errorsWhileComputingFlags)if(d){var x=new Set(Object.keys(d).filter(P=>{var M;return!((M=d[P])!=null&&M.failed)}));w=b({},n,Object.fromEntries(Object.entries(w).filter(P=>x.has(P[0])))),S=b({},o,Object.fromEntries(Object.entries(S||{}).filter(P=>x.has(P[0])))),k=b({},a,Object.fromEntries(Object.entries(k||{}).filter(P=>x.has(P[0]))))}else w=b({},n,w),S=b({},o,S),k=b({},a,k);return b({[Ds]:Object.keys(Ll(w)),[Lt]:w||{},[js]:S||{},[zn]:k||{},[Xr]:i.minimalFlagCalledEvents===!0},f?{[Ar]:f}:{},g?{[qs]:g}:{})}}(t,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),s,this.rt);r&&this.F(r),e||(this.xa=!1),this.Va(e)}}override(t,e){e===void 0&&(e=!1),this.rt.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:t,suppressWarning:e})}overrideFeatureFlags(t){this.Za(t)}Za(t){if(this.nn){if(t===!1)return this.q([Qe,Bt]),this.Va(),void Mt.info("All overrides cleared");if(B(t))return this.F({[Qe]:Ol(t)}),this.Va(),void Mt.info("Flag overrides set",{flags:t});if(t&&typeof t=="object"&&("flags"in t||"payloads"in t)){var e,s=t;this.ca=!!((e=s.suppressWarning)!==null&&e!==void 0&&e);var r={},i=s.flags,n=s.payloads;return i&&(r[Qe]=B(i)?Ol(i):i),n&&(r[Bt]=n),Object.keys(r).length&&this.F(r),i===!1&&n===!1?this.q([Qe,Bt]):i===!1?this.q(Qe):n===!1&&this.q(Bt),this.Va(),i===!1?Mt.info("Flag overrides cleared"):i&&Mt.info("Flag overrides set",{flags:i}),void(n===!1?Mt.info("Payload overrides cleared"):n&&Mt.info("Payload overrides set",{payloads:n}))}if(t&&typeof t=="object")return this.F({[Qe]:t}),this.Va(),void Mt.info("Flag overrides set",{flags:t});this.rt.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:t})}else this.rt.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(t){if(this.addFeatureFlagsHandler(t),this.ma){var e=this.Ga(),s=e.flags,r=e.flagVariants;try{t(s,r)}catch(i){this.rt.error("Error while running feature flags callback",i)}}return()=>this.removeFeatureFlagsHandler(t)}updateEarlyAccessFeatureEnrollment(t,e,s){var r=(this.Oa(Pr)||[]).find(l=>l.flagKey===t),i={["$feature_enrollment/"+t]:e},n={$feature_flag:t,$feature_enrollment:e,$set:i};r&&(n.$early_access_feature_name=r.name),s&&(n.$feature_enrollment_stage=s);var o=b({},this.getFlagVariants(),{[t]:e});this.F({[Ds]:Object.keys(Ll(o)),[Lt]:o,[lt]:b({},this.Oa(lt)||{},i)}),this.Va();try{var a;(a=this.nn)==null||a.capture("$feature_enrollment_update",n).catch(l=>{this.rt.error("Failed to capture early access feature enrollment",l)})}catch(l){this.rt.error("Failed to capture early access feature enrollment",l)}}getEarlyAccessFeatures(t,e,s){e===void 0&&(e=!1);var r=this.Oa(Pr);!r||e?this.Qa(t,s):t(r)}Qa(t,e){var s=this;return X(function*(){var r=s.nn;if(r){var i,n=e?"&"+e.map(a=>"stage="+a).join("&"):"";try{var o=yield r.sendRequest("/api/early_access_features/?token="+r.projectToken+n,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s.F({[Pr]:i=o.json.earlyAccessFeatures})}catch(a){return void s.rt.error("Early access feature request failed",a)}try{t(i)}catch(a){s.rt.error("Early access feature callback failed",a)}}})()}Ga(){var t=this.getFlags(),e=this.getFlagVariants();return{flags:t.filter(s=>e[s]),flagVariants:Object.keys(e).filter(s=>e[s]).reduce((s,r)=>(s[r]=e[r],s),{})}}Va(t){this.Fa();var e=this.Ga(),s=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach(i=>{try{i(s,r,{errorsLoading:t})}catch(n){this.rt.error("Error while running feature flags callback",n)}})}setPersonPropertiesForFlags(t,e){e===void 0&&(e=!0),this.Ka(t,e)}Ka(t,e){e===void 0&&(e=!0);var s=this.Oa(lt)||{},r=(t==null?void 0:t.$set)||(t!=null&&t.$set_once?{}:t),i=t==null?void 0:t.$set_once,n={};if(i)for(var o in i)({}).hasOwnProperty.call(i,o)&&(o in s||(n[o]=i[o]));this.F({[lt]:b({},s,n,r)}),e&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=b({},this.Oa(lt)||{});t.forEach(r=>{delete s[r]}),this.F({[lt]:s}),e&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(t){t===void 0&&(t=!0),this.q(lt),t&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(t,e){e===void 0&&(e=!0);var s=this.Oa(Dt)||{},r=b({},s);for(var i of Object.keys(t))r[i]=b({},s[i],t[i]);this.F({[Dt]:r}),e&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(t){if(t){var e=this.Oa(Dt)||{};this.F({[Dt]:b({},e,{[t]:{}})})}else this.q(Dt)}reset(){this.ba++,this.wa=!1,this.Fa(),this.ma=!1,this._a=!1,this.ka=!1,this.$anon_distinct_id=void 0,this.La(),this.ca=!1,this.Sa=0}}},hf={sessionRecording:class{get Ne(){return this._instance.config}get Mr(){return this._instance.persistence}get started(){var t;return!((t=this.Ja)==null||!t.isStarted)}get status(){var t,e;return this.Ya===Ms||this.Ya===xr?this.Ya:(t=(e=this.Ja)==null?void 0:e.status)!==null&&t!==void 0?t:this.Ya}constructor(t){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ya=Cl,this.Xa=void 0,this.eo=!1,this.io=(()=>{var e;if(F==null||!F.visibilityState||F.visibilityState==="visible")return!0;var s=m==null||(e=m.performance)==null||e.getEntriesByType==null?void 0:e.getEntriesByType("visibility-state");return!(s!=null&&s.length)||s.some(r=>r.name==="visible")})(),this.Ie=()=>{var e;(F==null?void 0:F.visibilityState)==="visible"&&(this.io=!0,(e=this.Ja)==null||e.setDocumentWasEverVisible==null||e.setDocumentWasEverVisible(!0))},this._instance=t,!this._instance.sessionManager)throw ot.error("started without valid sessionManager"),new Error(lo+" started without valid sessionManager. This is a bug.");if(this.Ne.cookieless_mode===dt)throw new Error(lo+' cannot be used with cookieless_mode="always"');F!=null&&F.addEventListener&&ie(F,"visibilitychange",this.Ie)}initialize(){this.startIfEnabledOrStop()}dispose(){this.eo=!0,F==null||F.removeEventListener==null||F.removeEventListener("visibilitychange",this.Ie),this.stopRecording()}get ro(){var t,e=!((t=this._instance.get_property(zt))==null||!t.enabled),s=!this.Ne.disable_session_recording,r=this.Ne.disable_session_recording||this._instance.consent.isOptedOut();return m&&e&&s&&!r}startIfEnabledOrStop(t){var e;if(!(this.eo||this.ro&&(e=this.Ja)!=null&&e.isStarted)){var s=!I(Object.assign)&&!I(Array.from);this.ro&&s?(this.no(t),ot.info("starting")):(this.Ya=Cl,this.stopRecording())}}no(t){var e,s,r;this.ro&&(this.Ya!==Ms&&this.Ya!==xr&&(this.Ya=Fl),R!=null&&(e=R.__PosthogExtensions__)!=null&&(e=e.rrweb)!=null&&e.record&&(s=R.__PosthogExtensions__)!=null&&s.initSessionRecording?this.so(t):(r=R.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,this.ao,i=>{if(i)return ot.error("could not load recorder",i);this.so(t)}))}stopRecording(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.stop()}oo(){var t,e;(t=this.Xa)==null||t.call(this),this.Xa=void 0,(e=this.Ja)==null||e.discard()}lo(){var t,e;(t=this.Mr)==null||t.unregister(Bo),(e=this.Mr)==null||e.unregister(eu)}uo(t,e){if(D(t))return null;var s,r=he(t)?t:parseFloat(t);return typeof(s=r)!="number"||!Number.isFinite(s)||0>s||s>1?(ot.warn(e+" must be between 0 and 1. Ignoring invalid value:",t),null):r}ho(t){if(this.Mr){var e,s,r=this.Mr,i=()=>{var n,o=t.sessionRecording===!1?void 0:t.sessionRecording,a=this.uo((n=this.Ne.session_recording)==null?void 0:n.sampleRate,"session_recording.sampleRate"),l=this.uo(o==null?void 0:o.sampleRate,"remote config sampleRate"),u=a??l;D(u)&&this.lo();var c=o==null?void 0:o.minimumDurationMilliseconds;r.register({[zt]:b({cache_timestamp:Date.now(),enabled:!!o},o,{networkPayloadCapture:b({capturePerformance:t.capturePerformance},o==null?void 0:o.networkPayloadCapture),canvasRecording:{enabled:o==null?void 0:o.recordCanvas,fps:o==null?void 0:o.canvasFps,quality:o==null?void 0:o.canvasQuality},sampleRate:u,minimumDurationMilliseconds:I(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,version:o==null?void 0:o.version,triggerGroups:o==null?void 0:o.triggerGroups})})};i(),(e=this.Xa)==null||e.call(this),this.Xa=(s=this._instance.sessionManager)==null?void 0:s.onSessionId(i)}}onRemoteConfig(t){var e=t.ok?t.config:void 0;return e&&"sessionRecording"in e?e.sessionRecording===!1?(this.ho(e),void this.oo()):(this.ho(e),void this.startIfEnabledOrStop()):(this.Ya===Ms&&(this.Ya=xr,ot.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(t,e){var s;e===void 0&&(e="log"),(s=this.Ja)!=null&&s.log?this.Ja.log(t,e):ot.warn("log called before recorder was ready")}get ao(){var t,e,s=(t=this._instance)==null||(t=t.persistence)==null?void 0:t.get_property(zt);return(s==null||(e=s.scriptConfig)==null?void 0:e.script)||"lazy-recorder"}do(){var t,e=this._instance.get_property(zt);if(!e)return!1;try{t=typeof e=="object"?e:JSON.parse(e)}catch(s){return ot.warn("persisted remote config for session recording is invalid and will be ignored",s),!1}return!D(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}so(t){var e,s,r;if(!this.eo){if((e=R.__PosthogExtensions__)==null||!e.initSessionRecording)return ot.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[lu]:!0});var i;if(this.Ja||(this.Ja=(i=R.__PosthogExtensions__)==null?void 0:i.initSessionRecording(this._instance,this.io),this.Ja._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.do())return this.Ya===xr||this.Ya===Ms?void 0:(this.Ya=Ms,ot.info("persisted remote config is stale, requesting fresh config before starting"),void new Tu(this._instance).load());this.Ya=Fl,(s=(r=this.Ja).setDocumentWasEverVisible)==null||s.call(r,this.io),this.Ja.start(t)}}onRRwebEmit(t){var e;(e=this.Ja)==null||e.onRRwebEmit==null||e.onRRwebEmit(t)}overrideLinkedFlag(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[su]:!0}),(t=this.Ja)==null||t.overrideLinkedFlag()}overrideSampling(){var t,e;this.Ja||(e=this.Mr)==null||e.register({[tu]:!0}),(t=this.Ja)==null||t.overrideSampling()}overrideTrigger(t){var e,s;this.Ja||(s=this.Mr)==null||s.register({[t==="url"?ru:iu]:!0}),(e=this.Ja)==null||e.overrideTrigger(t)}get sdkDebugProperties(){var t;return((t=this.Ja)==null?void 0:t.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(t,e){var s;return!((s=this.Ja)==null||!s.tryAddCustomEvent(t,e))}}},pf={autocapture:class{constructor(t){this.vo=!1,this.co=null,this.fo=!1,this.po=!1,this.instance=t,this.rageclicks=new xl(t.config.rageclick),this.mo=null}initialize(){this.startIfEnabled()}get Ne(){var t,e,s=te(this.instance.config.autocapture)?this.instance.config.autocapture:{};return s.url_allowlist=(t=s.url_allowlist)==null?void 0:t.map(r=>new RegExp(r)),s.url_ignorelist=(e=s.url_ignorelist)==null?void 0:e.map(r=>new RegExp(r)),s}yo(){if(this.isBrowserSupported()){if(m&&F){var t=s=>{s=s||(m==null?void 0:m.event);try{this.bo(s)}catch(r){vn.error("Failed to capture event",r)}};if(ie(F,"submit",t,{capture:!0}),ie(F,"change",t,{capture:!0}),ie(F,"click",t,{capture:!0}),this.Ne.capture_copied_text){var e=s=>{s=s||(m==null?void 0:m.event);try{this.bo(s,mn)}catch(r){vn.error("Failed to capture copy/cut event",r)}};ie(F,"copy",e,{capture:!0}),ie(F,"cut",e,{capture:!0})}}}else vn.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.vo&&(this.yo(),this.vo=!0)}onRemoteConfig(t){if(this.fo=!0,t.ok){var e=t.config;e.elementsChainAsString&&(this.po=e.elementsChainAsString);var s=e.autocapture_opt_out;Ge(s)&&(this.instance.persistence&&this.instance.persistence.register({[Ln]:s}),this.co=s),this.startIfEnabled()}else this.startIfEnabled()}setElementSelectors(t){this.mo=t}getElementSelectors(t){var e,s=[];return(e=this.mo)==null||e.forEach(r=>{var i=F==null?void 0:F.querySelectorAll(r);i==null||i.forEach(n=>{t===n&&s.push(r)})}),s}get isEnabled(){var t,e,s=(t=this.instance.persistence)==null?void 0:t.props[Ln],r=this.co,i=this.instance.Qi()&&!this.fo;if($e(r)&&!Ge(s)&&!i)return!1;var n=(e=this.co)!==null&&e!==void 0?e:!!s;return!!this.instance.config.autocapture&&!n}bo(t,e){if(e===void 0&&(e="$autocapture"),this.isEnabled){var s,r=rn(t);pu(r)&&(r=r.parentNode||null),e==="$autocapture"&&t.type==="click"&&t instanceof MouseEvent&&this.instance.config.rageclick&&(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,t.timeStamp||new Date().getTime())&&el(r,this.instance.config.rageclick)&&this.bo(t,"$rageclick");var i=e===mn;if(r&&function(d,h,p,f,g,v){var _;if(!m||Wo(d)||p!=null&&p.url_allowlist&&!Za(p.url_allowlist,v)||p!=null&&p.url_ignorelist&&Za(p.url_ignorelist,v))return!1;if(p!=null&&p.dom_event_allowlist){var w=p.dom_event_allowlist;if(w&&!w.some(E=>h.type===E))return!1}var S=yu(d,f),k=S.parentIsUsefulElement,x=S.targetElementList;if(!function(E,A){var $=A==null?void 0:A.element_allowlist;if(I($))return!0;var N,T=function(J){if($.some(z=>J.tagName.toLowerCase()===z))return{v:!0}};for(var O of E)if(N=T(O))return N.v;return!1}(x,p)||!Qn(x,p==null?void 0:p.css_selector_allowlist)||Qn(x,(_=p==null?void 0:p.css_selector_ignorelist)!==null&&_!==void 0?_:cp))return!1;try{var P=m.getComputedStyle(d);if(P&&P.getPropertyValue("cursor")==="pointer"&&h.type==="click")return!0}catch{}var M=d.tagName.toLowerCase();switch(M){case"html":return!1;case"form":return(g||["submit"]).indexOf(h.type)>=0;case"input":case"select":case"textarea":return(g||["change","click"]).indexOf(h.type)>=0;default:return k?(g||["click"]).indexOf(h.type)>=0:(g||["click"]).indexOf(h.type)>=0&&(Ho.indexOf(M)>-1||d.getAttribute("contenteditable")==="true")}}(r,t,this.Ne,i,i?["copy","cut"]:void 0,this.instance)){var n=tf(r,{e:t,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Ne.element_attribute_ignorelist,elementsChainAsString:this.po,disableCaptureUrlHashes:this.instance.config.disable_capture_url_hashes}),o=n.props;if(n.explicitNoCapture)return!1;var a=this.getElementSelectors(r);if(a&&a.length>0&&(o.$element_selectors=a),e===mn){var l,u=mu(m==null||(l=m.getSelection())==null?void 0:l.toString()),c=t.type||"clipboard";if(!u)return!1;o.$selected_content=u,o.$copy_type=c}return this.instance.capture(e,o),!0}}}isBrowserSupported(){return Se(F==null?void 0:F.querySelectorAll)}},historyAutocapture:class{constructor(t){var e;this._instance=t,this._o=(m==null||(e=m.location)==null?void 0:e.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(C.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.wo&&this.wo(),this.wo=void 0,C.info("History API monitoring stopped")}monitorHistoryChanges(){m&&m.history&&(this.ko("pushState"),this.ko("replaceState"),this.xo())}ko(t){var e;if(m&&((e=m.history[t])==null||!e.__posthog_wrapped__)){var s=this;(function(r,i,n){try{if(!(i in r))return kl;var o={next:r[i]},a=n(function(){for(var l=arguments.length,u=new Array(l),c=0;l>c;c++)u[c]=arguments[c];return o.next.apply(this,u)});return Se(a)&&(a.prototype=a.prototype||{},Object.defineProperties(a,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:o}})),r[i]=a,()=>{if(r[i]!==a)for(var l=r[i];Se(l)&&l.__posthog_layer__;){var u=l.__posthog_layer__;if(u.next===a)return void(u.next=o.next);l=u.next}else r[i]=o.next}}catch{return kl}})(m.history,t,r=>function(i,n,o){r.call(this,i,n,o),s.So(t)})}}So(t){try{var e,s=m==null||(e=m.location)==null?void 0:e.pathname;if(!s)return;s!==this._o&&this.isEnabled&&this._instance.capture(is,{navigation_type:t}),this._o=s}catch(r){C.error("Error capturing "+t+" pageview",r)}}xo(){if(!this.wo){var t=()=>{this.So("popstate")};ie(m,"popstate",t),this.wo=()=>{m&&m.removeEventListener("popstate",t)}}}},heatmaps:class{get Ne(){return this.instance.config}constructor(t){var e;this.Co=!1,this.vo=!1,this.Mo=null,this.instance=t,this.Co=!((e=this.instance.persistence)==null||!e.props[Bn]),this.rageclicks=new xl(t.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var t=5e3;return te(this.Ne.capture_heatmaps)&&this.Ne.capture_heatmaps.flush_interval_milliseconds&&(t=this.Ne.capture_heatmaps.flush_interval_milliseconds),t}get isEnabled(){return D(this.Ne.capture_heatmaps)?D(this.Ne.enable_heatmaps)?this.Co:this.Ne.enable_heatmaps:this.Ne.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.vo)return;rf.info("starting..."),this.To(),this.Ie()}else{var t;clearInterval((t=this.Mo)!==null&&t!==void 0?t:void 0),this.Eo(),this.getAndClearBuffer()}}onRemoteConfig(t){if(t.ok){var e=t.config;if("heatmaps"in e){var s=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Bn]:s}),this.Co=s,this.startIfEnabled()}}}getAndClearBuffer(){var t=this.R;return this.R=void 0,t}Io(t){yn(t.originalEvent)&&this.ke(t.originalEvent,"deadclick")}Ie(){this.Mo&&clearInterval(this.Mo),this.Mo=(F==null?void 0:F.visibilityState)==="visible"?setInterval(this.cr.bind(this),this.flushIntervalMilliseconds):null}To(){m&&F&&(this.Po=this.cr.bind(this),ie(m,ri,this.Po),this.Ro=t=>this.ke(t||(m==null?void 0:m.event)),ie(F,"click",this.Ro,{capture:!0}),this.Ao=t=>this.Fo(t||(m==null?void 0:m.event)),ie(F,"mousemove",this.Ao,{capture:!0}),this.Lo=new al(this.instance,mp,this.Io.bind(this)),this.Lo.startIfEnabledOrStop(),this.Oo=this.Ie.bind(this),ie(F,si,this.Oo),this.vo=!0)}Eo(){var t;m&&F&&(this.Po&&m.removeEventListener(ri,this.Po),this.Ro&&F.removeEventListener("click",this.Ro,{capture:!0}),this.Ao&&F.removeEventListener("mousemove",this.Ao,{capture:!0}),this.Oo&&F.removeEventListener(si,this.Oo),clearTimeout(this.Do),(t=this.Lo)==null||t.stop(),this.vo=!1)}$o(t,e){var s=this.instance.scrollManager.scrollY(),r=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),n=function(o,a,l){for(var u=o;u&&Ct(u)&&!Me(u,"body");){if(u===l)return!1;var c=void 0;try{var d,h,p;c=(d=(h=(p=u.ownerDocument)==null?void 0:p.defaultView)!==null&&h!==void 0?h:m)==null?void 0:d.getComputedStyle(u).position}catch{return!1}if(L(a,c))return!0;u=vu(u)}return!1}(rn(t),["fixed","sticky"],i);return{x:t.clientX+(n?0:r),y:t.clientY+(n?0:s),target_fixed:n,type:e}}ke(t,e){var s;if(e===void 0&&(e="click"),!Ya(t.target)&&yn(t)){var r=this.$o(t,e);(s=this.rageclicks)!=null&&s.isRageClick(t.clientX,t.clientY,new Date().getTime())&&el(rn(t),this.instance.config.rageclick)&&this.Vt(b({},r,{type:"rageclick"})),this.Vt(r)}}Fo(t){!Ya(t.target)&&yn(t)&&(clearTimeout(this.Do),this.Do=setTimeout(()=>{this.Vt(this.$o(t,"mousemove"))},500))}Vt(t){if(m){var e=this.Ne.disable_capture_url_hashes?It(m.location.href):m.location.href,s=this.Ne.custom_personal_data_properties,r=this.Ne.mask_personal_data_properties?[...vs,...s||[]]:[],i=tr(e,r,sr);this.R=this.R||{},this.R[i]||(this.R[i]=[]),this.R[i].push(t)}}cr(){this.R&&!gt(this.R)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:al,webVitalsAutocapture:class{constructor(t){var e;this.Co=!1,this.vo=!1,this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.No=()=>{clearTimeout(this.qo),this.qo=void 0,this.R.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.R.url},this.R.metrics.reduce((s,r)=>b({},s,{["$web_vitals_"+r.name+"_event"]:b({},r),["$web_vitals_"+r.name+"_value"]:r.value}),{}))),this.R={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.jo=s=>{var r;if(this.R=this.R||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},D(s==null?void 0:s.name)||D(s==null?void 0:s.value))Nt.error("Invalid metric received",s);else{var i=typeof s.navigationURL=="string"?s.navigationURL:void 0,n=this.Bo(i);if(!I(n)){var o=he(s.navigationId)||typeof s.navigationId=="string"?"navigation:"+s.navigationId:"url:"+n;if(!this.Ho||this.Ho>s.value){this.R.navigationKey!==o&&(this.No(),this.qo=setTimeout(this.No,this.flushToCaptureTimeoutMs)),I(this.R.navigationKey)&&(this.R.navigationKey=o,this.R.url=n),this.R.firstMetricTimestamp=I(this.R.firstMetricTimestamp)?Date.now():this.R.firstMetricTimestamp,s.attribution&&s.attribution.interactionTargetElement&&(s.attribution.interactionTargetElement=void 0);var a=(r=this._instance.sessionManager)==null?void 0:r.checkAndGetSessionAndWindowId(!0),l=b({},s,i?{navigationURL:n}:{},{$current_url:n,timestamp:Date.now()});I(a)||(l.$session_id=a.sessionId,l.$window_id=a.windowId),this.R.metrics.push(l),this.R.metrics.length===this.allowedMetrics.length&&this.No()}else Nt.error("Ignoring metric with value >= "+this.Ho,s)}}},this.Uo=()=>{if(!this.vo){var s,r,i,n,o=R.__PosthogExtensions__,a=o==null?void 0:o.postHogWebVitalsCallbacksByFlavor,l=(a==null?void 0:a[this.zo])||(this.zo==="web-vitals"&&I(a)?o==null?void 0:o.postHogWebVitalsCallbacks:void 0);if(I(l)||(s=l.onLCP,r=l.onCLS,i=l.onFCP,n=l.onINP),s&&r&&i&&n){var u={reportSoftNavs:this.useSoftNavs};this.allowedMetrics.indexOf("LCP")>-1&&s(this.jo.bind(this),u),this.allowedMetrics.indexOf("CLS")>-1&&r(this.jo.bind(this),u),this.allowedMetrics.indexOf("FCP")>-1&&i(this.jo.bind(this),u),this.allowedMetrics.indexOf("INP")>-1&&n(this.jo.bind(this),u),this.vo=!0}else Nt.error("web vitals callbacks not loaded - not starting")}},this._instance=t,this.Co=!((e=this._instance.persistence)==null||!e.props[Hn]),this.startIfEnabled()}get Wo(){return this._instance.config.capture_performance}get allowedMetrics(){var t,e,s=te(this.Wo)?(t=this.Wo)==null?void 0:t.web_vitals_allowed_metrics:void 0;return D(s)?((e=this._instance.persistence)==null?void 0:e.props[Wn])||["CLS","FCP","INP","LCP"]:s}get flushToCaptureTimeoutMs(){return(te(this.Wo)?this.Wo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var t=te(this.Wo)?this.Wo.web_vitals_attribution:void 0;return t!=null&&t}get useSoftNavs(){var t=te(this.Wo)?this.Wo.__preview_web_vitals_soft_navs:void 0;return t!=null&&t}get Ho(){var t=te(this.Wo)&&he(this.Wo.__web_vitals_max_value)?this.Wo.__web_vitals_max_value:Il;return t>0&&6e4>=t?Il:t}get isEnabled(){var t=re==null?void 0:re.protocol;if(t!=="http:"&&t!=="https:")return Nt.info("Web Vitals are disabled on non-http/https protocols"),!1;var e=te(this.Wo)?this.Wo.web_vitals:Ge(this.Wo)?this.Wo:void 0;return Ge(e)?e:this.Co}startIfEnabled(){this.isEnabled&&!this.vo&&(Nt.info("enabled, starting..."),this.ai(this.Uo))}onRemoteConfig(t){if(t.ok){var e=t.config;if("capturePerformance"in e){var s=te(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=te(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Hn]:s}),this._instance.persistence.register({[Wn]:r})),this.Co=s,this.startIfEnabled()}}}get zo(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}ai(t){var e=R.__PosthogExtensions__,s=this.zo,r=e==null?void 0:e.postHogWebVitalsCallbacksByFlavor;r!=null&&r[s]||s==="web-vitals"&&I(r)&&e!=null&&e.postHogWebVitalsCallbacks?t():e==null||e.loadExternalDependency==null||e.loadExternalDependency(this._instance,s,i=>{i?Nt.error("failed to load script",i):t()})}Bo(t){var e=t||(m==null?void 0:m.location.href);if(e){var s=this._instance.config.disable_capture_url_hashes?It(e):e,r=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...vs,...r||[]]:[];return tr(s,i,sr)}Nt.error("Could not determine current URL")}}},ff={exceptionObserver:class{constructor(t){var e;this.Uo=()=>{var s;if(m&&this.isEnabled&&(s=R.__PosthogExtensions__)!=null&&s.errorWrappingFunctions){var r=R.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=R.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,n=R.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.Vo&&this.Ne.capture_unhandled_errors&&(this.Vo=r(this.captureException.bind(this))),!this.Zo&&this.Ne.capture_unhandled_rejections&&(this.Zo=i(this.captureException.bind(this))),!this.Go&&this.Ne.capture_console_errors&&(this.Go=n(this.captureException.bind(this)))}catch(o){Ns.error("failed to start",o),this.Qo()}}},this._instance=t,this.Ko=!((e=this._instance.persistence)==null||!e.props[Dn]),this.Jo=new dh(b({},function(s){var r,i,n,o;return s===void 0&&(s={}),{refillRate:(r=(i=s.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:s.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(n=(o=s.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:s.__exceptionRateLimiterBucketSize)!==null&&n!==void 0?n:10}}(this._instance.config.error_tracking),{refillInterval:1e4,rt:Ns})),this.Ne=this.Yo(),this.startIfEnabledOrStop()}Yo(){var t=this._instance.config.capture_exceptions,e={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return te(t)?e=b({},e,t):(I(t)?this.Ko:t)&&(e=b({},e,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),e}get isEnabled(){return this.Ne.capture_console_errors||this.Ne.capture_unhandled_errors||this.Ne.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Ns.info("enabled"),this.Qo(),this.ai(this.Uo)):this.Qo()}ai(t){var e,s;(e=R.__PosthogExtensions__)!=null&&e.errorWrappingFunctions?t():(s=R.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"exception-autocapture",r=>{if(r)return Ns.error("failed to load script",r);t()})}Qo(){var t,e,s;(t=this.Vo)==null||t.call(this),this.Vo=void 0,(e=this.Zo)==null||e.call(this),this.Zo=void 0,(s=this.Go)==null||s.call(this),this.Go=void 0}onRemoteConfig(t){if(t.ok){var e=t.config;"autocaptureExceptions"in e&&(this.Ko=!!e.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[Dn]:this.Ko}),this.Ne=this.Yo(),this.startIfEnabledOrStop())}}onConfigChange(){this.Ne=this.Yo()}captureException(t){var e,s,r,i=(e=t==null||(s=t.$exception_list)==null||(s=s[0])==null?void 0:s.type)!==null&&e!==void 0?e:"Exception";this.Jo.consumeRateLimit(i)?Ns.info("Skipping exception capture because of client rate limiting.",{exception:i}):(r=this._instance.exceptions)==null||r.sendExceptionEvent(t)}},exceptions:class{constructor(t){var e,s;this.Xo=[],this.tl=new Fh([new Oh,new qh,new Bh,new Lh,new Wh,new Hh,new jh,new zh],function(r){for(var i=arguments.length,n=new Array(i>1?i-1:0),o=1;i>o;o++)n[o-1]=arguments[o];return function(a,l){l===void 0&&(l=0);for(var u=[],c=a.split(` +`),d=l;c.length>d;d++){var h=c[d];if(1024>=h.length){var p=Va.test(h)?h.replace(Va,"$1"):h;if(!p.match(/\S*Error: /)){for(var f of n){var g=f(p,r);if(g){u.push(g);break}}if(u.length>=50)break}}}return function(v){if(!v.length)return[];var _=Array.from(v);return _.reverse(),_.slice(0,50).map(w=>{return b({},w,{filename:w.filename||(S=_,S[S.length-1]||{}).filename,function:w.function||gs});var S})}(u)}}("web:javascript",Rh,Mh)),this._instance=t,this.Xo=(e=(s=this._instance.persistence)==null?void 0:s.get_property(jn))!==null&&e!==void 0?e:[],this.el=Zr(this.il()),this.rl=new Gh(this.el)}onConfigChange(){this.el=Zr(this.il()),this.rl.setConfig(this.el)}onRemoteConfig(t){var e,s,r;if(t.ok){var i=t.config;if("errorTracking"in i){var n=(e=(s=i.errorTracking)==null?void 0:s.suppressionRules)!==null&&e!==void 0?e:[],o=(r=i.errorTracking)==null?void 0:r.captureExtensionExceptions;this.Xo=n,this._instance.persistence&&this._instance.persistence.register({[jn]:this.Xo,[Un]:o})}}}get nl(){var t,e=!!this._instance.get_property(Un),s=this._instance.config.error_tracking.captureExtensionExceptions;return(t=s??e)!==null&&t!==void 0&&t}buildProperties(t,e){return this.tl.buildFromUnknown(t,{syntheticException:e==null?void 0:e.syntheticException,mechanism:{handled:e==null?void 0:e.handled}})}addExceptionStep(t,e){if(this.el.enabled)try{if(!W(t)||t.trim().length===0)return void Ze.warn("Ignoring exception step because message must be a non-empty string");var s=function(n){if(!n)return{sanitizedProperties:{},droppedKeys:[]};var o=[];return{sanitizedProperties:Object.keys(n).reduce((a,l)=>Vh.has(l)?(o.push(l),a):(a[l]=n[l],a),{}),droppedKeys:o}}(this.sl(e)),r=s.sanitizedProperties,i=s.droppedKeys;i.length>0&&Ze.warn("Ignoring reserved exception step fields",{droppedKeys:i}),this.rl.add(b({[Jr]:t,[Yr]:new Date().toISOString()},r))}catch(n){Ze.error("Failed to add exception step. Ignoring breadcrumb.",n)}}sendExceptionEvent(t){try{var e=t.$exception_list;if(this.al(e)){if(this.ol(e))return this.ll("Exception dropped: matched a suppression rule"),void Ze.info("Skipping exception capture because a suppression rule matched");if(!this.nl&&this.ul(e))return this.ll("Exception dropped: thrown by a browser extension"),void Ze.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.hl(e))return this.ll("Exception dropped: thrown by the PostHog SDK"),void Ze.info("Skipping exception capture because it was thrown by the PostHog SDK")}var s=this.el.enabled&&D(t.$exception_steps)?this.dl(t):t,r=typeof(n=globalThis._posthogReleaseId)=="string"&&n.length>0?n:void 0;r&&(s.$release_id=r);try{var i=this._instance.capture("$exception",s,{_noTruncate:!0,_batchKey:"exceptionEvent",Wn:!0});return i&&this.rl.clear(),i}catch(o){return Ze.error("Failed to capture exception event. Dropping this exception.",o),void this.rl.clear()}}catch(o){return void Ze.error("Failed to process exception event. Ignoring this exception.",o)}var n}dl(t){try{var e=this.rl.getAttachable();return e.length===0?t:b({},t,{$exception_steps:e})}catch(s){return Ze.error("Failed to read buffered exception steps. Capturing exception without steps.",s),t}}ll(t){this.el.enabled&&this.rl.add({[Jr]:t,[Yr]:new Date().toISOString()})}sl(t){return te(t)?b({},t):{}}il(){var t,e;return(t=(e=this._instance.config.error_tracking)==null?void 0:e.exception_steps)!==null&&t!==void 0?t:{}}ol(t){if(t.length===0)return!1;try{var e=t.reduce((s,r)=>{var i=r.type,n=r.value;return W(i)&&i.length>0&&s.$exception_types.push(i),W(n)&&n.length>0&&s.$exception_values.push(n),s},{$exception_types:[],$exception_values:[]});return this.Xo.some(s=>{var r=s.values.map(i=>{var n=Gu[i.operator],o=e[i.key];if(!n||!o)return!1;var a=B(i.value)?i.value:[i.value];return a.length>0&&n(a,o)});return s.type==="OR"?r.some(Boolean):r.every(Boolean)})}catch(s){return Ze.warn("Failed to evaluate suppression rules. Capturing the exception.",s),!1}}ul(t){return t.flatMap(e=>{var s,r;return(s=(r=e.stacktrace)==null?void 0:r.frames)!==null&&s!==void 0?s:[]}).some(e=>e.filename&&e.filename.startsWith("chrome-extension://"))}hl(t){if(t.length>0){var e,s,r,i,n=(e=(s=t[0].stacktrace)==null?void 0:s.frames)!==null&&e!==void 0?e:[],o=n[n.length-1];return(r=o==null||(i=o.filename)==null?void 0:i.includes("posthog.com/static"))!==null&&r!==void 0&&r}return!1}al(t){return!D(t)&&B(t)}}},gf=b({productTours:class{get Mr(){return this._instance.persistence}constructor(t){this.vl=null,this.cl=null,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(t.ok){var e=t.config;if("productTours"in e){var s,r;if(this.Mr&&this.Mr.register({[Lo]:!!e.productTours}),!wn(this._instance))return!this.vl&&D((s=this.Mr)==null?void 0:s.props[Us])||kr.info("product tours disabled; stopping and clearing cached tours"),(r=this.vl)==null||r.stop(),this.vl=null,void this.clearCache();this.loadIfEnabled()}}}loadIfEnabled(){!this.vl&&wn(this._instance)&&this.ai(()=>this.fl())}ai(t){var e,s;(e=R.__PosthogExtensions__)!=null&&e.generateProductTours?t():(s=R.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"product-tours",r=>{r?kr.error("Could not load product tours script",r):t()})}fl(){var t;!this.vl&&(t=R.__PosthogExtensions__)!=null&&t.generateProductTours&&(this.vl=R.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(t,e){if(e===void 0&&(e=!1),!B(this.cl)||e){var s=this.Mr;if(s){var r=s.props[Us];if(B(r)&&!e)return this.cl=r,void t(r,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",timestampMode:"query",callback:i=>{if(wn(this._instance)){var n=i.statusCode;if(n!==200||!i.json){var o="Product Tours API could not be loaded, status: "+n;return n===0?i.error||kr.warn(o):kr.error(o),void t([],{isLoaded:!1,error:o})}var a=B(i.json.product_tours)?i.json.product_tours:[];this.cl=a,s&&s.register({[Us]:a}),t(a,{isLoaded:!0})}else t([],{isLoaded:!0})}})}else t(this.cl,{isLoaded:!0})}getActiveProductTours(t){D(this.vl)?t([],{isLoaded:!1,error:"Product tours not loaded"}):this.vl.getActiveProductTours(t)}showProductTour(t){var e;(e=this.vl)==null||e.showTourById(t)}previewTour(t){this.vl?this.vl.previewTour(t):this.ai(()=>{var e;this.fl(),(e=this.vl)==null||e.previewTour(t)})}dismissProductTour(){var t;(t=this.vl)==null||t.dismissTour("user_clicked_skip")}nextStep(){var t;(t=this.vl)==null||t.nextStep()}previousStep(){var t;(t=this.vl)==null||t.previousStep()}clearCache(){var t;this.cl=null,(t=this.Mr)==null||t.unregister(Us)}resetTour(t){var e;(e=this.vl)==null||e.resetTour(t)}resetAllTours(){var t;(t=this.vl)==null||t.resetAllTours()}cancelPendingTour(t){var e;(e=this.vl)==null||e.cancelPendingTour(t)}}},Pi),mf={siteApps:class{constructor(t){this.pl=0,this._instance=t,this.gl=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}ml(t,e){if(e){var s=this.globalsForEvent(e);this.gl.push(s),this.gl.length>1e3&&(this.gl=this.gl.slice(10))}}get siteAppLoaders(){var t;return(t=R._POSTHOG_REMOTE_CONFIG)==null||(t=t[this._instance.config.token])==null?void 0:t.siteApps}initialize(){if(this.isEnabled){var t=this._instance._addCaptureHook(this.ml.bind(this));this.yl=()=>{t(),this.gl=[],this.yl=void 0}}}globalsForEvent(t){var e,s,r,i,n,o,a;if(!t)throw new Error("Event payload is required");var l={},u=this._instance.get_property("$groups")||[],c=this._instance.get_property("$stored_group_properties")||{};for(var d of Object.entries(c)){var h=d[0];l[h]={id:u[h],type:h,properties:d[1]}}var p=t.$set_once,f=t.$set;return{event:b({},_c(t,nf),{properties:b({},t.properties,f?{$set:b({},(e=(s=t.properties)==null?void 0:s.$set)!==null&&e!==void 0?e:{},f)}:{},p?{$set_once:b({},(r=(i=t.properties)==null?void 0:i.$set_once)!==null&&r!==void 0?r:{},p)}:{}),elements_chain:(n=(o=t.properties)==null?void 0:o.$elements_chain)!==null&&n!==void 0?n:"",distinct_id:(a=t.properties)==null?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:l}}bl(t){var e,s=(e=t.tagName)==null?void 0:e.toLowerCase();return s==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(t)||(Ye.error("prepare_external_dependency_stylesheet returned null"),null):s==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(t)||(Ye.error("prepare_external_dependency_script returned null"),null):t}_l(){var t,e,s,r,i,n,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};var l=F==null?void 0:F.defaultView,u=l==null||(t=l.Node)==null?void 0:t.prototype;if(!l||!u)return()=>{};if(this.pl++,this.wl)return this.kl();var c=[],d=this,h=new WeakSet,p=(v,_,w)=>{if(v!=null&&v[_]){var S=v[_];v[_]=w(S),c.push(()=>{v[_]=S})}},f=v=>{if(h.has(v))return v;var _=d.bl(v);return _&&h.add(_),_},g=v=>v.map(_=>typeof _=="string"?_:f(_)).filter(_=>!$e(_));return p(u,"appendChild",v=>function(_){var w=f(_);return w?v.call(this,w):_}),p(u,"insertBefore",v=>function(_,w){var S=f(_);return S?v.call(this,S,w):_}),p(u,"replaceChild",v=>function(_,w){var S=f(_);return S?v.call(this,S,w):w}),[(e=l.Element)==null?void 0:e.prototype,(s=l.Document)==null?void 0:s.prototype,(r=l.DocumentFragment)==null?void 0:r.prototype].forEach(v=>{p(v,"append",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))}),p(v,"prepend",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))})}),[(i=l.Element)==null?void 0:i.prototype,(n=l.CharacterData)==null?void 0:n.prototype,(o=l.DocumentType)==null?void 0:o.prototype].forEach(v=>{p(v,"before",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))}),p(v,"after",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];return _.apply(this,g(S))}),p(v,"replaceWith",_=>function(){for(var w=arguments.length,S=new Array(w),k=0;w>k;k++)S[k]=arguments[k];var x=g(S);return S.length&&!x.length?void 0:_.apply(this,x)})}),p((a=l.Element)==null?void 0:a.prototype,"insertAdjacentElement",v=>function(_,w){var S=f(w);return S?v.call(this,_,S):null}),this.wl=()=>{c.forEach(v=>v()),this.wl=void 0},this.kl()}kl(){var t=!1;return()=>{var e;t||(t=!0,this.pl--,this.pl===0&&((e=this.wl)==null||e.call(this)))}}xl(t,e){e===void 0&&(e=!0);var s=this._l();try{var r=t(s);return e&&s(),r}catch(i){throw s(),i}}setupSiteApp(t){var e=this.apps[t.id],s=()=>{var o;!e.errored&&this.gl.length&&(Ye.info("Processing "+this.gl.length+" events for site app with id "+t.id),this.gl.forEach(a=>this.xl(()=>e.processEvent==null?void 0:e.processEvent(a))),e.processedBuffer=!0),Object.values(this.apps).every(a=>a.processedBuffer||a.errored)&&((o=this.yl)==null||o.call(this))},r=!1,i=o=>{e.errored=!o,e.loaded=!0,Ye.info("Site app with id "+t.id+" "+(o?"loaded":"errored")),r&&s()};try{var n=this.xl(o=>t.init({posthog:this._instance,callback(a){o(),i(a)}}),!1).processEvent;n&&(e.processEvent=n),r=!0}catch(o){Ye.error(Pl+t.id,o),i(!1)}if(r&&e.loaded)try{s()}catch(o){Ye.error("Error while processing buffered events PostHog app with config id "+t.id,o),e.errored=!0}}Sl(){var t=this.siteAppLoaders||[];for(var e of t)this.apps[e.id]={id:e.id,loaded:!1,errored:!1,processedBuffer:!1};for(var s of t)this.setupSiteApp(s)}Cl(t){var e=this;if(Object.keys(this.apps).length!==0){var s=this.globalsForEvent(t),r=function(n){try{e.xl(()=>n.processEvent==null?void 0:n.processEvent(s))}catch(o){Ye.error("Error while processing event "+t.event+" for site app "+n.id,o)}};for(var i of Object.values(this.apps))r(i)}}onRemoteConfig(t){var e,s,r,i=this;if((e=this.siteAppLoaders)!=null&&e.length)return this.isEnabled?(this.Sl(),void this._instance.on("eventCaptured",l=>this.Cl(l))):void Ye.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((s=this.yl)==null||s.call(this),t.ok){var n=t.config;if((r=n.siteApps)!=null&&r.length)if(this.isEnabled){var o=function(){var l,u=a.id,c=a.url;R["__$$ph_site_app_"+u]=i._instance,(l=R.__PosthogExtensions__)==null||l.loadSiteApp==null||l.loadSiteApp(i._instance,c,d=>{if(d)return Ye.error(Pl+u,d)})};for(var a of n.siteApps)o()}else Ye.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}}},vf={tracingHeaders:class{constructor(t){this.Ml=void 0,this.Tl=void 0,this.El=void 0,this.Uo=()=>{var e,s,r=this.Il();r?(I(this.Ml)&&(this.Ml=(e=R.__PosthogExtensions__)==null||(e=e.tracingHeadersPatchFns)==null?void 0:e._patchXHR(r,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),I(this.Tl)&&(this.Tl=(s=R.__PosthogExtensions__)==null||(s=s.tracingHeadersPatchFns)==null?void 0:s._patchFetch(r,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.Qo()},this._instance=t}initialize(){this.startIfEnabledOrStop()}ai(t){var e,s;(e=R.__PosthogExtensions__)!=null&&e.tracingHeadersPatchFns?t():(s=R.__PosthogExtensions__)==null||s.loadExternalDependency==null||s.loadExternalDependency(this._instance,"tracing-headers",r=>{if(r)return sf.error("failed to load script",r);t()})}Pl(){var t,e;return(t=(e=this._instance.config.tracing_headers)!==null&&e!==void 0?e:this._instance.config.addTracingHeaders)!==null&&t!==void 0?t:this._instance.config.__add_tracing_headers}Il(){var t=this.Pl();return B(t)?(B(this.El)?this.El.splice(0,this.El.length,...t):this.El=[...t],t.length>0?this.El:void 0):(B(this.El)&&this.El.splice(0),this.El=t||void 0,this.El)}Qo(){var t,e;(t=this.Ml)==null||t.call(this),(e=this.Tl)==null||e.call(this),this.Ml=void 0,this.Tl=void 0}startIfEnabledOrStop(){this.Il()?this.ai(this.Uo):this.Qo()}}},_f=b({surveys:class{get Ne(){return this._instance.config}constructor(t){this.Rl=void 0,this._surveyManager=null,this.Al=!1,this.Fl=[],this.Ll=null,this.Ol=null,this._instance=t,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this.Ne.disable_surveys){if(!t.ok)return V.warn("Remote config unavailable. Not loading surveys.");var e=t.config.surveys;if(D(e))return V.warn("Flags not loaded yet. Not loading surveys.");var s=B(e);this.Rl=s?e.length>0:e,V.info("flags response received, isSurveysEnabled: "+this.Rl),this.loadIfEnabled()}}reset(){try{var t;(t=this._surveyEventReceiver)==null||t.reset(),localStorage.removeItem("lastSeenSurveyDate");for(var e=[],s=0;slocalStorage.removeItem(i))}catch{}}loadIfEnabled(){if(!this._surveyManager)if(this.Al)V.info("Already initializing surveys, skipping...");else if(this.Ne.disable_surveys)V.info(Al);else if(this.Ne.cookieless_mode&&this._instance.consent.isOptedOut())V.info("Not loading surveys in cookieless mode without consent.");else{var t=R==null?void 0:R.__PosthogExtensions__;if(t){if(!I(this.Rl)||this.Ne.advanced_enable_surveys){var e=this.Rl||this.Ne.advanced_enable_surveys;this.Al=!0;try{var s=t.generateSurveys;if(s)return void this.Dl(s,e);var r=t.loadExternalDependency;if(!r)return void this.$l(Do);r(this._instance,"surveys",i=>{i||!t.generateSurveys?this.$l("Could not load surveys script",i):this.Dl(t.generateSurveys,e)})}catch(i){throw this.$l("Error initializing surveys",i),i}finally{this.Al=!1}}}else V.error("PostHog Extensions not found.")}}Dl(t,e){this._surveyManager=t(this._instance,e),this._surveyEventReceiver=new lf(this._instance),V.info("Surveys loaded successfully"),this.Nl({isLoaded:!0})}$l(t,e){V.error(t,e),this.Nl({isLoaded:!1,error:t})}onSurveysLoaded(t){return this.Fl.push(t),this._surveyManager&&this.Nl({isLoaded:!0}),()=>{this.Fl=this.Fl.filter(e=>e!==t)}}getSurveys(t,e){if(e===void 0&&(e=!1),this.Ne.disable_surveys)return V.info(Al),t([]);var s,r=this._instance.get_property(qn);if(r&&!e)return t(r,{isLoaded:!0}),void(this.ql()&&this.getSurveys(()=>{},!0));typeof Promise<"u"&&this.Ll?this.Ll.then(i=>t(i.surveys,i.context)):(typeof Promise<"u"&&(this.Ll=new Promise(i=>{s=i})),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Ne.token),method:"GET",timestampMode:"query",timeout:this.Ne.surveys_request_timeout_ms,callback:i=>{var n;this.Ll=null;var o=i.statusCode;if(o!==200||!i.json){var a="Surveys API could not be loaded, status: "+o;o!==0?V.error(a):i.error||V.warn(a),this.Ol=Date.now();var l={isLoaded:!1,error:a};return t([],l),void(s==null||s({surveys:[],context:l}))}this.Ol=null;var u,c=i.json.surveys||[],d=c.filter(p=>function(f){return!(!f.start_date||f.end_date)}(p)&&(Ju(p)||function(f){var g;return!((g=f.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)}(p)));d.length>0&&((u=this._surveyEventReceiver)==null||u.register(d)),(n=this._instance.persistence)==null||n.register({[qn]:c,[Qr]:Date.now()});var h={isLoaded:!0};t(c,h),s==null||s({surveys:c,context:h})}}))}ql(){return this.jl()&&!this.Ll&&!this.Bl()}jl(){var t=this._instance.get_property(Qr);return he(t)&&Date.now()-t>3e5}Bl(){return he(this.Ol)&&3e5>Date.now()-this.Ol}markSurveyAsSeen(t,e){var s,r={id:t,current_iteration:(s=e==null?void 0:e.iteration)!==null&&s!==void 0?s:null};Zu(r);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}}Nl(t){for(var e of this.Fl)try{if(!t.isLoaded)return e([],t);this.getSurveys(e)}catch(s){V.error("Error in survey callback",s)}}getActiveMatchingSurveys(t,e){if(e===void 0&&(e=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(t,e);V.warn("init was not called")}Hl(t){var e=null;return this.getSurveys(s=>{var r;e=(r=s.find(i=>i.id===t))!==null&&r!==void 0?r:null}),e}Ul(t){if(D(this._surveyManager))return{eligible:!1,reason:Ir};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyEligibility(e):{eligible:!1,reason:"Survey not found"}}zl(t){if(D(this._surveyManager))return{eligible:!1,reason:Ir};var e=typeof t=="string"?this.Hl(t):t;return e?this._surveyManager.checkSurveyRenderability(e):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(t){if(D(this._surveyManager))return V.warn("init was not called"),{visible:!1,disabledReason:Ir};var e=this.zl(t);return{visible:e.eligible,disabledReason:e.reason}}canRenderSurveyAsync(t,e){return D(this._surveyManager)?(V.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Ir})):new Promise(s=>{this.getSurveys(r=>{var i,n=(i=r.find(a=>a.id===t))!==null&&i!==void 0?i:null;if(n){var o=this.zl(n);s({visible:o.eligible,disabledReason:o.reason})}else s({visible:!1,disabledReason:"Survey not found"})},e)})}renderSurvey(t,e,s){var r;if(D(this._surveyManager))V.warn("init was not called");else{var i=typeof t=="string"?this.Hl(t):t;if(i!=null&&i.id)if(Wp.includes(i.type)){var n=F==null?void 0:F.querySelector(e);if(n)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(V.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout(()=>{var o,a;V.info("Rendering survey "+i.id+" with delay of "+((o=i.appearance)==null?void 0:o.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,n,s),V.info("Survey "+i.id+" rendered")},1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,n,s);V.warn("Survey element not found")}else V.warn("Surveys of type "+i.type+" cannot be rendered in the app");else V.warn("Survey not found")}}displaySurvey(t,e){var s;if(D(this._surveyManager))V.warn("init was not called");else{var r=this.Hl(t);if(r){var i=r;if((s=r.appearance)!=null&&s.surveyPopupDelaySeconds&&e.ignoreDelay&&(i=b({},r,{appearance:b({},r.appearance,{surveyPopupDelaySeconds:0})})),e.displayType!==to.Popover&&e.initialResponses&&V.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),e.ignoreConditions===!1){var n=this.Ul(r);if(!n.eligible)return void V.warn("Survey is not eligible to be displayed: ",n.reason)}e.displayType!==to.Inline?this._surveyManager.handlePopoverSurvey(i,e):this.renderSurvey(i,e.selector,e.properties)}else V.warn("Survey not found")}}cancelPendingSurvey(t){D(this._surveyManager)?V.warn("init was not called"):this._surveyManager.cancelSurvey(t)}handlePageUnload(){var t;(t=this._surveyManager)==null||t.handlePageUnload==null||t.handlePageUnload()}}},Pi),yf={toolbar:class{constructor(t){this.instance=t}Wl(t){R.ph_toolbar_state=t}Vl(){var t;return(t=R.ph_toolbar_state)!==null&&t!==void 0?t:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(t,e,s){if(t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),Xn(this.instance.config)||!m||!F)return!1;t=t??m.location,s=s??m.history;try{if(!e){try{m.localStorage.setItem("test","test"),m.localStorage.removeItem("test")}catch{return!1}e=m==null?void 0:m.localStorage}var r,i=cf||ai(t.hash,"__posthog")||ai(t.hash,"state"),n=i?Ka(()=>JSON.parse(atob(decodeURIComponent(i))))||Ka(()=>JSON.parse(decodeURIComponent(i))):null;return n&&n.action==="ph_authorize"?((r=n).source="url",r&&Object.keys(r).length>0&&(n.desiredHash?t.hash=n.desiredHash:s?s.replaceState(s.state,"",t.pathname+t.search):t.hash="")):((r=JSON.parse(e.getItem($l)||"{}")).source="localstorage",delete r.userIntent),!(!r.token||this.instance.config.token!==r.token||(this.loadToolbar(r),0))}catch{return!1}}Zl(t){var e=R.ph_load_toolbar||R.ph_load_editor;!D(e)&&Se(e)?e(t,this.instance):Rl.warn("No toolbar load function found")}loadToolbar(t){var e=!(F==null||!F.getElementById(hu));if(!m||e)return!1;var s=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,r=b({token:this.instance.config.token},t,{apiURL:this.instance.requestRouter.endpointFor("ui")},s?{instrument:!1}:{});if(m.localStorage.setItem($l,JSON.stringify(b({},r,{source:void 0}))),this.Vl()===2)this.Zl(r);else if(this.Vl()===0){var i;this.Wl(1),(i=R.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this.instance,"toolbar",n=>{if(n)return Rl.error("[Toolbar] Failed to load",n),void this.Wl(0);this.Wl(2),this.Zl(r)}),ie(m,"turbolinks:load",()=>{this.Wl(0),this.loadToolbar(r)})}return!0}Gl(t){return this.loadToolbar(t)}maybeLoadEditor(t,e,s){return t===void 0&&(t=void 0),e===void 0&&(e=void 0),s===void 0&&(s=void 0),this.maybeLoadToolbar(t,e,s)}}},wf=b({experiments:ye},Pi),bf={conversations:class{constructor(t){this.Ql=void 0,this._conversationsManager=null,this.Kl=!1,this.Jl=null,this.Yl=!1,this._instance=t}initialize(){this.loadIfEnabled()}onRemoteConfig(t){if(!this._instance.config.disable_conversations&&(this.Xl=t.ok,t.ok)){var e=t.config.conversations;D(e)||(Ge(e)?this.Ql=e:(this.Ql=e.enabled,this.Jl=e),this.loadIfEnabled())}}reset(){var t;(t=this._conversationsManager)==null||t.reset(),this._conversationsManager=null,this.Ql=void 0,this.Jl=null,this.Xl=void 0,this.Yl=!1}loadIfEnabled(){if(!(this._conversationsManager||this.Kl||this._instance.config.disable_conversations||Xn(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var t=R==null?void 0:R.__PosthogExtensions__;if(t&&!I(this.Ql)&&this.Ql)if(this.Jl&&this.Jl.token){this.Kl=!0;try{var e=t.initConversations;if(e)return this.tu(e),void(this.Kl=!1);var s=t.loadExternalDependency;if(!s)return void this.eu(Do);s(this._instance,"conversations",r=>{r||!t.initConversations?this.eu("Could not load conversations script",r):this.tu(t.initConversations),this.Kl=!1})}catch(r){this.eu("Error initializing conversations",r),this.Kl=!1}}else Ue.error("Conversations enabled but missing token in remote config.")}}tu(t){if(this.Jl)try{this._conversationsManager=t(this.Jl,this._instance),this.Yl=!1,Ue.info("Conversations loaded successfully")}catch(e){this.eu("Error completing conversations initialization",e)}else Ue.error("Cannot complete initialization: remote config is null")}eu(t,e){Ue.error(t,e),this._conversationsManager=null,this.Kl=!1,this.Yl=!0}show(){this._conversationsManager?this._conversationsManager.show():Ue.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ql===!0&&!$e(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Xn(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.Xl===!1?"remote_config_failed":I(this.Ql)?this.Xl?"disabled_in_project":"remote_config_pending":this.Ql?D(this.Jl)||!this.Jl.token?"missing_token":R!=null&&R.__PosthogExtensions__?this.Kl?"initializing":this.Yl?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.isVisible())!==null&&t!==void 0&&t}sendMessage(t,e,s){var r=this;return X(function*(){return r._conversationsManager?r._conversationsManager.sendMessage(t,e,s):(Ue.warn(Ot),null)})()}getMessages(t,e){var s=this;return X(function*(){return s._conversationsManager?s._conversationsManager.getMessages(t,e):(Ue.warn(Ot),null)})()}markAsRead(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.markAsRead(t):(Ue.warn(Ot),null)})()}getTickets(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.getTickets(t):(Ue.warn(Ot),null)})()}requestRestoreLink(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.requestRestoreLink(t):(Ue.warn(Ot),null)})()}restoreFromToken(t){var e=this;return X(function*(){return e._conversationsManager?e._conversationsManager.restoreFromToken(t):(Ue.warn(Ot),null)})()}restoreFromUrlToken(){var t=this;return X(function*(){return t._conversationsManager?t._conversationsManager.restoreFromUrlToken():(Ue.warn(Ot),null)})()}getCurrentTicketId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getCurrentTicketId())!==null&&t!==void 0?t:null}getWidgetSessionId(){var t,e;return(t=(e=this._conversationsManager)==null?void 0:e.getWidgetSessionId())!==null&&t!==void 0?t:null}Xn(){var t;(t=this._conversationsManager)==null||t.setIdentity()}ts(){var t;(t=this._conversationsManager)==null||t.clearIdentity()}}},Ef={logs:class{constructor(t){var e,s=this;this.iu=!1,this.ru=!1,this.rt=se("[logs]"),this.nu=b({},this.rt,{error(){for(var r=arguments.length,i=new Array(r),n=0;r>n;n++)i[n]=arguments[n];i.some(jl)||s.rt.error(...i)}}),this.tr=[],this.su=[],this.Sa=0,this.au=()=>{var r,i;this.Sa=0,(r=this.ou)==null||r.onReconnect(),(i=this.lu)==null||i.onReconnect()},this._instance=t,this._instance&&(e=this._instance.config.logs)!=null&&e.captureConsoleLogs&&(this.iu=!0),m&&ie(m,"online",this.au)}uu(t,e,s,r){var i,n=function(o,a){var l,u,c,d,h,p,f,g=(l=o==null?void 0:o.flushIntervalMs)!==null&&l!==void 0?l:3e3,v=(u=o==null?void 0:o.maxBufferSize)!==null&&u!==void 0?u:100,_=a!=null&&a.consoleCapture?void 0:(c=o==null?void 0:o.maxLogsPerInterval)!==null&&c!==void 0?c:1e3,w=I(_)?Math.max(v,2048):Math.max(v,_),S=o==null?void 0:o.resourceAttributes;return{serviceName:(d=(h=S==null?void 0:S["service.name"])!==null&&h!==void 0?h:o==null?void 0:o.serviceName)!==null&&d!==void 0?d:a==null?void 0:a.serviceNameDefault,serviceVersion:(p=S==null?void 0:S["service.version"])!==null&&p!==void 0?p:o==null?void 0:o.serviceVersion,environment:(f=S==null?void 0:S["deployment.environment"])!==null&&f!==void 0?f:o==null?void 0:o.environment,resourceAttributes:S,beforeSend:o==null?void 0:o.beforeSend,flushIntervalMs:g,maxBufferSize:v,maxQueueSize:w,maxBatchRecordsPerPost:100,rateCapWindowMs:g,maxLogsPerInterval:_,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}((i=this._instance)==null||(i=i.config)==null?void 0:i.logs,s);return[new kh(this.hu(t,e),n,this.nu,()=>this.du(),o=>o(),void 0,r),n]}vu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.ou||this.cu!==e){var s;(s=this.ou)==null||s.reset(),this.cu=e;var r=this.uu(()=>this.tr,i=>{this.tr=i});this.ou=r[0],this.fu=r[1]}return this.ou}pu(){var t,e=(t=this._instance)==null||(t=t.config)==null?void 0:t.logs;if(!this.lu||this.gu!==e){var s;(s=this.lu)==null||s.reset(),this.gu=e;var r=this.uu(()=>this.su,i=>{this.su=i},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Dl);this.lu=r[0],this.mu=r[1]}return this.lu}initialize(){this.loadIfEnabled()}onRemoteConfig(t){var e;if(t.ok){var s=(e=t.config.logs)==null?void 0:e.captureConsoleLogs;!D(s)&&s&&(this.iu=!0,this.loadIfEnabled())}}reset(){var t,e;this.tr=[],(t=this.ou)==null||t.reset(),this.su=[],(e=this.lu)==null||e.reset(),this.Sa=0}captureLog(t){this.vu().captureLog(t)}he(t){this.pu().captureLog(t)}get logger(){return this.yu||(this.yu={trace:(t,e)=>this.captureLog({body:t,level:"trace",attributes:e}),debug:(t,e)=>this.captureLog({body:t,level:"debug",attributes:e}),info:(t,e)=>this.captureLog({body:t,level:"info",attributes:e}),warn:(t,e)=>this.captureLog({body:t,level:"warn",attributes:e}),error:(t,e)=>this.captureLog({body:t,level:"error",attributes:e}),fatal:(t,e)=>this.captureLog({body:t,level:"fatal",attributes:e})}),this.yu}flushLogs(t){t?this.bu(t):(this.ou&&this.ou.flush().catch(e=>this._u(e)),this.lu&&this.lu.flush().catch(e=>this._u(e)))}_u(t){jl(t)||this.rt.error("PostHog logs flush failed:",t)}loadIfEnabled(){if(this.iu&&!this.ru){var t=R==null?void 0:R.__PosthogExtensions__;if(t){var e=t.loadExternalDependency;e?e(this._instance,"logs",s=>{var r;s||(r=t.logs)==null||!r.initializeLogs?this.rt.error("Could not load logs script",s):(t.logs.initializeLogs(this._instance),this.ru=!0)}):this.rt.error(Do)}else this.rt.error("PostHog Extensions not found.")}}hu(t,e){var s=this._instance;return{get isDisabled(){return!1},get optedOut(){return!s.is_capturing()},getPersistedProperty:r=>r===ct.LogsQueue?t():void 0,setPersistedProperty(r,i){var n;r===ct.LogsQueue&&e((n=i)!==null&&n!==void 0?n:[])},Ot:r=>this.Ot(r),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Ot(t){return new Promise(e=>{if(xu(this.Sa,3))e({kind:"fatal",error:En(void 0,"logs endpoint is unreachable, dropping batch")});else{var s=!1,r=n=>{s||(s=!0,clearTimeout(i),e(n))},i=setTimeout(()=>{this.rt.warn("Logs request timed out before receiving a response"),r({kind:"retry-later",error:En(void 0,"logs request timed out")})},9e4);this._instance._send_request({method:"POST",url:this.wu(),data:t,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:n=>{var o=n.statusCode;if(this.ku(o),o>=200&&300>o)r({kind:"ok"});else if(o===413)r({kind:"too-large"});else if(o!==0&&o!==429&&500>o)r({kind:"fatal",error:new Error("logs request failed with status "+o)});else{var a;o===0?(n.error||this.rt.warn("Logs request failed before receiving an HTTP response"),r({kind:"retry-later",error:En(n.error,"logs request failed before receiving an HTTP response")})):r({kind:"retry-later",error:(a=n.error)!==null&&a!==void 0?a:new Error("logs request failed with status "+o)})}}})}})}ku(t){(t!==0||this._instance.__loaded)&&(this.Sa=ku(t,this.Sa,3,()=>this.rt.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}bu(t){this.tr.length>0&&this.xu(t,this.tr,this.fu,Y.LIB_NAME,e=>{this.tr=e}),this.su.length>0&&this.xu(t,this.su,this.mu,Dl,e=>{this.su=e})}xu(t,e,s,r,i){if(e.length!==0){var n=e.map(a=>a.record);i([]);var o=Jc(n,Kc(s,Y.LIB_NAME,Y.LIB_VERSION),r,Y.LIB_VERSION);this._instance._send_request({method:"POST",url:this.wu(),data:o,compression:"best-available",batchKey:"logs",transport:t})}}wu(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}du(){var t,e={};if(e.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var s=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0),r=s.windowId,i=s.sessionStartTimestamp,n=s.lastActivityTimestamp;e.sessionId=s.sessionId,e.windowId=r,D(i)||(e.sessionStartTimestamp=i),D(n)||(e.lastActivityTimestamp=n)}if(R!=null&&(t=R.location)!=null&&t.href&&(e.currentUrl=this._instance.config.disable_capture_url_hashes?It(R.location.href):R.location.href),this._instance.featureFlags){var o=this._instance.featureFlags.getFlags();o&&o.length>0&&(e.activeFeatureFlags=o)}return e}}},Sf={metrics:class{constructor(t){this.rt=se("[metrics]"),this._instance=t}initialize(){}vu(){var t,e,s=(t=this._instance)==null||(t=t.config)==null?void 0:t.metrics;return this.ou&&this.cu===s||((e=this.ou)==null||e.reset(),this.cu=s,this.ou=new Ih(this.hu(),function(r){var i,n,o,a,l,u=r==null?void 0:r.resourceAttributes;return{serviceName:(i=u==null?void 0:u["service.name"])!==null&&i!==void 0?i:r==null?void 0:r.serviceName,serviceVersion:(n=u==null?void 0:u["service.version"])!==null&&n!==void 0?n:r==null?void 0:r.serviceVersion,environment:(o=u==null?void 0:u["deployment.environment"])!==null&&o!==void 0?o:r==null?void 0:r.environment,resourceAttributes:u,beforeSend:r==null?void 0:r.beforeSend,flushIntervalMs:(a=r==null?void 0:r.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(l=r==null?void 0:r.maxSeriesPerFlush)!==null&&l!==void 0?l:1e3}}(s),this.rt)),this.ou}count(t,e,s){e===void 0&&(e=1),this.vu().count(t,e,s)}gauge(t,e,s){this.vu().gauge(t,e,s)}histogram(t,e,s){this.vu().histogram(t,e,s)}flush(t){if(!this.ou)return Promise.resolve();if(t){var e=this.ou.drainWindow();return e&&this.Jt(e,t),Promise.resolve()}return this.ou.flush().catch(s=>this.rt.error("PostHog metrics flush failed:",s))}reset(){var t;(t=this.ou)==null||t.reset()}hu(){var t=this._instance,e=this;return{get isDisabled(){return!1},get optedOut(){return!t.is_capturing()},Jt:s=>e.Jt(s),getLibraryId:()=>Y.LIB_NAME,getLibraryVersion:()=>Y.LIB_VERSION}}Jt(t,e){return new Promise(s=>{var r=!1,i=o=>{r||(r=!0,clearTimeout(n),s(o))},n=setTimeout(()=>i({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(b({method:"POST",url:this.Su(),data:t,compression:"best-available",batchKey:"metrics"},e&&{transport:e},{fireCallbackOnDrop:!0,callback(o){var a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==429&&500>a)i({kind:"fatal",error:new Error("metrics request failed with status "+a)});else{var l;i({kind:"retry-later",error:(l=o.error)!==null&&l!==void 0?l:new Error("metrics request failed with status "+a)})}}}))})}Su(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}},xf=b({},Pi,hf,pf,ff,gf,mf,_f,vf,yf,wf,bf,Ef,Sf);Te.__defaultExtensionClasses=b({},xf);var td=function(){Y.SDK_DIST_CHANNEL="npm";var t=Ks[ns]=new Te;return function(){function e(){e.done||(e.done=!0,Qu=!1,Z(Ks,function(s){s._dom_loaded()}))}F!=null&&F.addEventListener?F.readyState==="complete"?e():ie(F,"DOMContentLoaded",e,{capture:!1}):m&&C.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")}(),t}();const sd="CodeFile",rd="GeneratedCode",kf={CustomAction:"A",CustomWidget:"W",CustomFunction:"F",CustomClass:"C",CodeFile:"C"};function xt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function co(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function If(t={},e=0){const s=co(t.artifactType||t.type||sd),r=co(t.artifactName||t.name||t.fileName||`${rd}-${e+1}`);return`${s||"artifact"}-${r||e+1}`}function id(t={},e=0){const s=xt(t),r=s.artifactType||s.type||sd,i=s.artifactName||s.name||rd;let n=s.fileName||i;return n.endsWith(".dart")||(n+=".dart"),{id:co(s.id)||If({...s,artifactType:r,artifactName:i,fileName:n},e),artifactType:r,artifactName:i,fileName:n,deployPath:s.deployPath||"",description:s.description||"",code:s.code||s.content||"",dependencies:nd(s.dependencies),imports:Array.isArray(s.imports)?s.imports:[],publicApi:Array.isArray(s.publicApi)?s.publicApi:[],relationships:od(s.relationships),deployStatus:s.deployStatus||"pending",review:s.review||null,metadata:xt(s.metadata),codeType:s.codeType||kf[r]||"O"}}function nd(t){return t?Array.isArray(t)?t.map(e=>{if(typeof e=="string")return{name:e,version:null,inferred:!1};const s=xt(e),r=s.name||s.package;return r?{name:r,version:s.version||null,versionRequired:!!(s.versionRequired||s.required),inferred:!!s.inferred,...s.reason?{reason:s.reason}:{}}:null}).filter(Boolean):Object.entries(xt(t)).map(([e,s])=>({name:e,version:s||null,inferred:!1})):[]}function od(t){return t?(Array.isArray(t)?t:[t]).map(e=>{const s=xt(e);return!s.from&&!s.to?null:{from:s.from||null,to:s.to||null,type:s.type||"uses",description:s.description||""}}).filter(Boolean):[]}function uo(t){if(typeof t!="string")return null;const e=t.trim();if(!e)return null;try{return JSON.parse(e)}catch{const s=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(!s)return null;try{return JSON.parse(s[1].trim())}catch{return null}}}function rr(t,e={}){const s=[],r=typeof t=="string"?uo(t):t,n=xt(r||{});!r&&typeof t=="string"&&s.push("Structured bundle parse failed; using legacy single-artifact fallback.");const o=Array.isArray(n.artifacts)?n.artifacts:[{artifactType:n.artifactType||e.artifactType,artifactName:n.artifactName||e.artifactName,fileName:n.fileName||e.fileName,description:n.description,code:n.code||e.code||(typeof t=="string"?t:""),dependencies:n.dependencies||e.dependencies,relationships:n.relationships||e.relationships}];o.forEach((d,h)=>{!(d!=null&&d.artifactType)&&!(d!=null&&d.type)&&s.push(`Artifact ${h+1} has no artifactType; it will deploy as a standalone code file under lib/custom_code/ root.`)});const a=o.map((d,h)=>id(d,h)),l=new Map(o.map((d,h)=>{var p;return[xt(d).id,(p=a[h])==null?void 0:p.id]}).filter(([d,h])=>d&&h)),u=d=>l.get(d)||d,c=od(n.relationships||e.relationships).map(d=>({...d,from:d.from?u(d.from):d.from,to:d.to?u(d.to):d.to}));return{schemaVersion:n.schemaVersion||e.schemaVersion||null,id:n.id||e.id||"bundle-current",title:n.title||n.name||e.title||"Generated artifact bundle",description:n.description||e.description||"",artifacts:a,dependencies:nd(n.dependencies||e.dependencies),relationships:c,deployOrder:Array.isArray(n.deployOrder)?n.deployOrder.map(u):a.map(d=>d.id),warnings:[...s,...Array.isArray(n.warnings)?n.warnings:[]],metadata:xt(n.metadata)}}function hi(t){return rr(t).artifacts[0]||id()}function _t(t){if(typeof t!="string")return t??"";const e=t.trim();if(!e)return"";try{return JSON.parse(e)}catch{return t}}function ys(t){return JSON.stringify(t,null,2)}function Cf(t){return ys({task:"architect",userRequest:String(t??"")})}function Ff(t){const e=_t(t);return e&&typeof e=="object"&&typeof e.task=="string"?ys(e):ys({task:"generate_bundle",bundleSpec:e})}function Pf(t){return ys({task:"review_bundle",generatedBundle:_t(t),outputRequirements:{bundleReview:["status","score","summary","manualActions","findings"],scoreRange:[0,100],eachArtifact:["id","review.status","review.findings"],manualActions:{definition:"Setup the developer must perform by hand in the FlutterFlow editor that FlutterFlow will NOT do for them.",exclude:["creating the Custom Action, Widget or Code File itself - deploying the code creates it","declaring parameters or return values FlutterFlow derives from the function signature","anything that resolves as a side effect of using the action or widget in the editor","generic advice such as testing, reviewing or rebuilding the app"],preferEmpty:"Return an empty array when nothing qualifies - an empty list is the expected result for most bundles."}}})}function Go(t,e=null){const s={stage:t};return e!=null&&(s.bundle=_t(e)),s}function Af({bundleSpec:t,artifactBundle:e,bundleReview:s,artifactId:r,userFeedback:i}){return ys({task:"regenerate_artifact",artifactId:r,bundleSpec:_t(t),artifactBundle:_t(e),bundleReview:_t(s),userFeedback:String(i)})}function ad({bundleSpec:t,artifactBundle:e,bundleReview:s,userFeedback:r}){return ys({task:"regenerate_bundle",bundleSpec:_t(t),artifactBundle:_t(e),bundleReview:_t(s),userFeedback:String(r??"")})}const Ul={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"},$f=["sanitizationResult","modelArmor","modelArmorResult","data","result","error"];function Oe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Rf(t){return Oe(t)?typeof t.filterMatchState=="string"||typeof t.invocationResult=="string"||Array.isArray(t.matchedFilters)||Oe(t.filterSummary)||Oe(t.filterResults):!1}function ld(t,e=0){if(!Oe(t)||e>3)return null;if(Rf(t))return t;for(const s of $f){const r=t[s];if(Oe(r)){const i=ld(r,e+1);if(i)return i}}return null}function pi(t){return Array.isArray(t)?t.some(pi):Oe(t)?t.matched===!0||t.matchState==="MATCH_FOUND"?!0:Object.values(t).some(pi):!1}function ho(t){return Array.isArray(t)?t.some(ho):Oe(t)?typeof t.executionState=="string"&&t.executionState!=="EXECUTION_SUCCESS"?!0:Object.values(t).some(ho):!1}function cd(t){return{csamFilterFilterResult:"csam",maliciousUriFilterResult:"malicious_uris",piAndJailbreakFilterResult:"pi_and_jailbreak",raiFilterResult:"rai",sdpFilterResult:"sdp",virusScanFilterResult:"virus_scan"}[t]||t}function Tf(t,e){if(Oe(t))for(const[s,r]of Object.entries(t)){if(!Oe(r))continue;const i=Oe(r.categories)?r.categories:{},n=Object.entries(i).filter(([,o])=>Oe(o)&&o.matched===!0).map(([o])=>o);n.length>0?n.forEach(o=>e.add(o)):r.matched===!0&&e.add(cd(s))}}function Nf(t,e){var r;if(!t)return;const s=Array.isArray(t)?t.flatMap(i=>Oe(i)?Object.entries(i):[]):Object.entries(t);for(const[i,n]of s){if(!pi(n))continue;const o=cd(i),a=((r=n==null?void 0:n.raiFilterResult)==null?void 0:r.raiFilterTypeResults)||(o==="rai"?n==null?void 0:n.raiFilterTypeResults:null),l=Oe(a)?Object.entries(a).filter(([,u])=>pi(u)).map(([u])=>u):[];l.length>0?l.forEach(u=>e.add(u)):e.add(o)}}function Mf(t){return Ul[t]?Ul[t]:String(t).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/_/g," ").toLowerCase()}function Hl(t){return t.length<=1?t[0]||"content that did not pass":t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t.at(-1)}`}function Of(t){const e=ld(t);if(!e)return null;const s=new Set(Array.isArray(e.matchedFilters)?e.matchedFilters:[]);Tf(e.filterSummary,s),Nf(e.filterResults,s);const r=e.blocked===!0||e.filterMatchState==="MATCH_FOUND"||s.size>0,i=e.invocationResult||null,n=ho(e.filterSummary||e.filterResults);return!r&&!n&&!["PARTIAL","FAILURE"].includes(i)?null:{kind:r?"blocked":"unavailable",invocationResult:i,matchedFilters:[...s]}}function Lf(t,e){const s=Of(t);if(!s)return null;const r=[...new Set(s.matchedFilters.map(Mf))],i=s.kind==="blocked",n=new Error(i?`Safety screening blocked this pipeline step for ${Hl(r)}.`:"Safety screening could not be completed. Please try again.");return n.name="ModelArmorError",n.code=i?"MODEL_ARMOR_BLOCKED":"MODEL_ARMOR_UNAVAILABLE",n.isModelArmor=!0,n.pipelineStep=e,n.userTitle=i?"Request blocked for safety":"Safety check unavailable",n.userMessage=i?`The safety check detected ${Hl(r)}. Edit your request to remove or rephrase the flagged content, then run the pipeline again.`:"The safety service did not finish all of its checks. Please wait a moment and run the pipeline again.",n.retryExplanation=i?"Trying another model would not change this safety decision.":"A fallback model was not attempted because safety screening must complete first.",n.matchedFilters=s.matchedFilters,n}function Bf(t){return String(t||"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,"")}function Wl(t){const e=/^(import|export|part|library|class|enum|extension|typedef|mixin|abstract|const|final|var|late)\b/,s=[];for(const r of Bf(t).split(` +`)){if(!/^[A-Za-z_$]/.test(r)||e.test(r))continue;const i=r.match(/^[\w$<>,?\s[\]]+?\s([a-zA-Z_$][\w$]*)\s*\(/);i&&s.push(i[1])}return s}function Ko(t,e){const s=t.replace(/\.dart$/,"");if(e==="W")return s.replace(/(^|_)(\w)/g,(r,i,n)=>n.toUpperCase());if(e==="A"){const r=s.replace(/(^|_)(\w)/g,(i,n,o)=>o.toUpperCase());return r.charAt(0).toLowerCase()+r.slice(1)}return e==="F"?"CustomFunctions":e==="C"?t.endsWith(".dart")?t:`${t}.dart`:s}async function zl(t){const e=new TextEncoder().encode(String(t||"")),s=await globalThis.crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(s),r=>r.toString(16).padStart(2,"0")).join("")}async function Df(t,e=new Map){const s={},r=new Set;for(const[o,a]of t.entries()){if(a.type==="D"||a.type==="O")continue;const l=Ko(o,a.type),u={old_identifier_name:l,new_identifier_name:l,type:a.type,is_deleted:!1,current_checksum:await zl(a.content)},c=e.get(a.path);if(c!==void 0&&(u.original_checksum=await zl(c)),s[o]=u,a.type==="F"){const d=Wl(a.content);(d.length>0?d:[a.functionName].filter(Boolean)).forEach(p=>r.add(p))}}const i=new Set(Wl(e.get("lib/flutter_flow/custom_functions.dart")||"")),n={functions_to_rename:[],functions_to_delete:[],functions_to_add:Array.from(r).filter(o=>!i.has(o))};return{fileMapContents:JSON.stringify(s),functionsMapContents:JSON.stringify(n)}}const jf=new Set(["CustomWidget","CustomAction","CustomFunction","CustomClass","CodeFile"]),ql={CustomWidget:"custom_code/widgets/",CustomAction:"custom_code/actions/",CustomFunction:"flutter_flow/custom_functions.dart",CustomClass:"custom_code/",CodeFile:"custom_code/"},Uf=new Set(["void","dynamic","String","int","double","num","bool","Color","DateTime","DateTimeRange","LatLng","FFPlace","FFUploadedFile","DocumentReference","List"]),Hf=["Struct","Record"],Wf=[{id:"required-public-param",severity:"error",message:"CustomWidget constructor uses `required` on a parameter FlutterFlow can leave unset. FlutterFlow omits unset Define Parameters fields from the constructor call, so the widget will not compile when placed. Make the parameter optional and nullable (`this.value` with `final double? value`), or give it a constructor default (`this.value = 0.0`).",detect:t=>Sn(t).some(e=>/\brequired\s+this\.\w+/.test(e)),pos:"class W extends StatefulWidget { const W({required this.value}); final double value; }",neg:`class _P { const _P({required this.t}); final double t; } +class W extends StatefulWidget { const W({this.value}); final double? value; }`},{id:"non-nullable-public-field",severity:"error",message:"CustomWidget declares a non-nullable field with no constructor default. FlutterFlow omits unset Define Parameters fields, so the emitted call cannot supply it. Make the field nullable (`final double? value`) or give the parameter a default (`this.value = 0.0`).",detect:t=>Sn(t).some(e=>{const s=/^\s*final\s+(?:double|int|String|bool|Color|num)\s+(\w+)\s*;/gm;let r;for(;(r=s.exec(e))!==null;){const i=r[1];if(!(new RegExp(`this\\.${i}\\s*=(?!=)`).test(e)||new RegExp(`[:,]\\s*${i}\\s*=(?!=)`).test(e)))return!0}return!1}),pos:`class W extends StatefulWidget { const W({required this.value}); final double value; }`,neg:`class _P { @@ -14,7 +14,7 @@ class W extends StatefulWidget { final double value; }`},{id:"asset-without-anchor",severity:"warning",message:'CustomWidget calls Image.asset with a path arriving as a String parameter. An asset reaches the build only when a FlutterFlow widget NODE references it - a filename passed as a parameter does not count, so the image renders as a broken-image icon on device. "Download Unused Project Assets" does not fix it (FlutterFlow issues 522, 2271, 3799). Keep something in the UI referencing the file, or load it over the network instead.',detect:t=>/Image\.asset\s*\(/.test(t)&&/final\s+String\??\s+\w*[Pp]ath\b/.test(t),pos:`class W extends StatefulWidget { final String? imagePath; } var x = Image.asset(widget.imagePath);`,neg:`class W extends StatefulWidget { final String? imagePath; } -var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>En(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { +var x = Image.network(widget.imagePath);`},{id:"unsupported-param-type",severity:"error",message:"CustomWidget exposes a Flutter data type FlutterFlow cannot express as a Define Parameter: TextStyle, BoxShadow, FontWeight, FontStyle, TextDirection, TextAlign, EdgeInsets, Offset, Alignment/AlignmentGeometry, Border, BorderRadius, BoxDecoration, BoxConstraints, BorderSide, Gradient, or ThemeData. FlutterFlow's supported data types (docs.flutterflow.io/resources/data-representation/data-types) are only int, double, bool, string, Color, Image, DateTime, Json, LatLng, and the FF objects, so this parameter cannot be configured in the editor and the widget will not place or compile. Expose primitives instead (color, fontSize as double?, fontWeight via a custom enum, doubles for spacing).",detect:t=>Sn(t).some(e=>/final\s+(TextStyle|BoxShadow|FontWeight|FontStyle|TextDirection|TextAlign|EdgeInsets|Offset|Alignment(?:Geometry)?|Border(?:Radius|Side)?|BoxDecoration|BoxConstraints|Gradient|LinearGradient|RadialGradient|ThemeData)\??\s+\w+\s*;/.test(e)),pos:`class W extends StatefulWidget { const W({this.textStyle}); final TextStyle? textStyle; @override _S createState() => _S(); @@ -25,39 +25,49 @@ class _S extends State { @override Widget build(BuildContext c) => const Size @override _S createState() => _S(); } class _S extends State { @override Widget build(BuildContext c) => Padding(padding: const EdgeInsets.all(8), child: const SizedBox()); }`}];function Xe(t,e,s){return{artifactId:t.id,artifactName:t.artifactName,artifactType:t.artifactType,severity:e,message:s}}function ir(t){let e="",s=0;for(;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function jf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let i=s.index+s[0].length-1;iUf(t).usable);function Wf(t=""){const e=ir(t);return Hf.filter(s=>s.detect(e)).map(({id:s,severity:r,message:i})=>({id:s,severity:r,message:i}))}function zf(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let i=r.index+6,n=null;const o=i;for(;io;if(t[i]==="<"){const u=Df(t,i);if(!u||(n=u.inner.replace(/\s+/g," ").trim(),i=u.end,!/\s/.test(t[i]||"")))continue;for(;izl(o.functionName)===r);if(i)return i;const n=o=>!o.functionName.startsWith("_");return s.find(n)||s[0]}function Pi(t=""){return Array.from(ir(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function qf(t="",e=""){var s;return((s=Go(t,e))==null?void 0:s.returnType)||null}function ql(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Vf(t,e){const s=Pi(e);if(s.length===0)return null;const i=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>ql(l)===i)||s.length>1)return null;const[o]=s,a=`${ql(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function Gf(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Kf(t,e,s=""){var a;const r=(a=Go(e,s))==null?void 0:a.functionName;if(!r)return null;const i=String(t||"").split("/").pop(),n=ad(i,"A");if(n===r)return null;const o=`${Gf(r)}.dart`;return`File name "${i}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${n}" and reports Action "${n}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${n}".`}function Jf(t="",e=""){return Go(t,e)!==null}function Yf(t,e=new Set){return((t==null?void 0:t.match(/[A-Za-z_]\w*/g))||[]).filter(r=>Of.has(r)?!1:!Lf.some(n=>r.endsWith(n))||e.has(r))}function Zf(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=qf(t,e),i=Yf(r,s);if(i.length===0)return null;const[n]=i;let o;return s.has(n)?o=`uses Code File type "${n}", which FlutterFlow cannot process as an Action Return Value`:r===n?o="is not a FlutterFlow Action Return Value":o=`uses type "${n}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function Xf(t,e={}){const s=[],r=t.fileName||"",i=t.code||"";if(Nf.has(t.artifactType)||s.push(Xe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Xe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!i.trim())return s.push(Xe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)||s.push(Xe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const n of Wf(i))s.push(Xe(t,n.severity,n.message))}if(t.artifactType==="CustomAction"&&!Jf(i,t.artifactName)&&s.push(Xe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const n=e.declaredTypes||new Set(Pi(i)),o=Zf(i,{functionName:t.artifactName,declaredTypes:n});o&&s.push(Xe(t,"error",o));const a=Kf(r,i,t.artifactName);a&&s.push(Xe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)&&s.push(Xe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const n=Vf(r,i);n&&s.push(Xe(t,"info",n))}return s}function Qf(t){const e=Array.isArray(t==null?void 0:t.artifacts)?t.artifacts:[],s=new Set(e.flatMap(n=>Pi(n.code||""))),r=e.flatMap(n=>Xf(n,{declaredTypes:s})),i=e.map(n=>({artifactId:n.id,fileName:n.fileName,pathHint:Wl[n.artifactType]||Wl.CodeFile}));return{valid:r.every(n=>n.severity!=="error"),findings:r,deployHints:i}}const Vl="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Gl(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function eg(t=""){const e=t.indexOf(Vl);return e===-1?t:t.slice(e+Vl.length).replace(/^\s*\n/,"")}const tg=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function sg(t="",e=""){const s=eg(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(Gl).filter(Boolean)),i=s.split(` -`).filter(n=>{const o=Gl(n);return o===null||!r.has(o)?!0:!tg.test(n)}).join(` -`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+i}const rg=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function ig(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const i=s.versionRequired||s.required;return e[r]=i&&s.version||"",e},{})}function lg(t){const e=new Map,s=new Map,r=[];for(const i of t)e.has(i.fileName)?r.push(`Duplicate deploy file name "${i.fileName}" for artifacts "${e.get(i.fileName)}" and "${i.artifactId}".`):e.set(i.fileName,i.artifactId),s.has(i.path)?r.push(`Duplicate deploy path "${i.path}" for artifacts "${s.get(i.path)}" and "${i.artifactId}".`):s.set(i.path,i.artifactId);return r}function cg(t,e={}){const s=Array.isArray(t==null?void 0:t.artifacts)?t.artifacts:[],i=(e.selectedArtifactIds||(t==null?void 0:t.deployOrder)||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),n=[...(t==null?void 0:t.warnings)||[]];let o=[];i.forEach(p=>{const f=ag(p),g=p.fixedCode||p.code||"",v=p.codeType||ng[p.artifactType]||Me.OTHER;g.trim()||n.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:v,path:p.deployPath||og(f,v),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Me.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:v})=>v.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:v})=>`// ${v.artifactId} +`;)s++;e+=" "}else if(r==="/*"){for(s+=2;s"&&(s--,s===0))return{inner:t.slice(e+1,r),end:r+1};return null}function qf(t,e){const s=new RegExp(`class\\s+${e}\\b[^{]*\\{`).exec(t);if(!s)return null;let r=0;for(let i=s.index+s[0].length-1;iVf(t).usable);function Kf(t=""){const e=ir(t);return Gf.filter(s=>s.detect(e)).map(({id:s,severity:r,message:i})=>({id:s,severity:r,message:i}))}function Jf(t){const e=[],s=t.matchAll(/\bFuture\b/g);for(const r of s){let i=r.index+6,n=null;const o=i;for(;io;if(t[i]==="<"){const u=zf(t,i);if(!u||(n=u.inner.replace(/\s+/g," ").trim(),i=u.end,!/\s/.test(t[i]||"")))continue;for(;iVl(o.functionName)===r);if(i)return i;const n=o=>!o.functionName.startsWith("_");return s.find(n)||s[0]}function Ai(t=""){return Array.from(ir(t).matchAll(/\b(?:class|enum)\s+([A-Za-z_]\w*)/g),e=>e[1])}function Yf(t="",e=""){var s;return((s=Jo(t,e))==null?void 0:s.returnType)||null}function Gl(t){return String(t||"").replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").toLowerCase()}function Zf(t,e){const s=Ai(e);if(s.length===0)return null;const i=String(t||"").split("/").pop().replace(/\.dart$/,"");if(s.some(l=>Gl(l)===i)||s.length>1)return null;const[o]=s,a=`${Gl(o)}.dart`;return`File name "${t}" does not match declared class "${o}". FlutterFlow accepts this, but naming the file "${a}" keeps the Code File recognisable in the editor.`}function ud(t){return String(t||"").replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,"")}function Xf(t,e,s=""){var a;const r=(a=Jo(e,s))==null?void 0:a.functionName;if(!r)return null;const i=String(t||"").split("/").pop(),n=Ko(i,"A");if(n===r)return null;const o=`${ud(r)}.dart`;return`File name "${i}" does not match Action "${r}". FlutterFlow derives the action from the file name, so it looks for "${n}" and reports Action "${n}" declaration not found. Rename the file to "${o}" - FlutterFlow puts an underscore before every capital - or rename the function to "${n}".`}function Qf(t="",e=""){return Jo(t,e)!==null}function eg(t,e=new Set){return((t==null?void 0:t.match(/[A-Za-z_]\w*/g))||[]).filter(r=>Uf.has(r)?!1:!Hf.some(n=>r.endsWith(n))||e.has(r))}function tg(t,{functionName:e="",declaredTypes:s=new Set}={}){const r=Yf(t,e),i=eg(r,s);if(i.length===0)return null;const[n]=i;let o;return s.has(n)?o=`uses Code File type "${n}", which FlutterFlow cannot process as an Action Return Value`:r===n?o="is not a FlutterFlow Action Return Value":o=`uses type "${n}", which is not a FlutterFlow Action Return Value`,`CustomAction return type "${r}" ${o}. Return JSON (Future) or an existing FlutterFlow Data Type (*Struct) instead.`}function sg(t,e={}){const s=[],r=t.fileName||"",i=t.code||"";if(jf.has(t.artifactType)||s.push(Xe(t,"error",`Unsupported artifact type "${t.artifactType}".`)),r.endsWith(".dart")||s.push(Xe(t,"error","FlutterFlow custom code artifacts must use .dart files.")),!i.trim())return s.push(Xe(t,"warning","Generated artifact has no Dart code yet.")),s;if(t.artifactType==="CustomWidget"){/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)||s.push(Xe(t,"warning","CustomWidget code should declare a widget class extending StatelessWidget or StatefulWidget."));for(const n of Kf(i))s.push(Xe(t,n.severity,n.message))}if(t.artifactType==="CustomAction"&&!Qf(i,t.artifactName)&&s.push(Xe(t,"warning","CustomAction code should expose an async Future function callable from FlutterFlow.")),t.artifactType==="CustomAction"){const n=e.declaredTypes||new Set(Ai(i)),o=tg(i,{functionName:t.artifactName,declaredTypes:n});o&&s.push(Xe(t,"error",o));const a=Xf(r,i,t.artifactName);a&&s.push(Xe(t,"error",a))}if(t.artifactType==="CustomFunction"&&/class\s+\w+\s+extends\s+(StatelessWidget|StatefulWidget)/.test(i)&&s.push(Xe(t,"warning","CustomFunction should be a callable function, not a widget class.")),t.artifactType==="CustomClass"||t.artifactType==="CodeFile"){const n=Zf(r,i);n&&s.push(Xe(t,"info",n))}return s}function rg(t){const e=Array.isArray(t==null?void 0:t.artifacts)?t.artifacts:[],s=new Set(e.flatMap(n=>Ai(n.code||""))),r=e.flatMap(n=>sg(n,{declaredTypes:s})),i=e.map(n=>({artifactId:n.id,fileName:n.fileName,pathHint:ql[n.artifactType]||ql.CodeFile}));return{valid:r.every(n=>n.severity!=="error"),findings:r,deployHints:i}}const Kl="// DO NOT REMOVE OR MODIFY THE CODE ABOVE!";function Jl(t){return(/^\s*import\s+['"]([^'"]+)['"]/.exec(t)||[])[1]||null}function ig(t=""){const e=t.indexOf(Kl);return e===-1?t:t.slice(e+Kl.length).replace(/^\s*\n/,"")}const ng=/^\s*import\s+['"][^'"]+['"]\s*;\s*(?:\/\/.*)?$/;function og(t="",e=""){const s=ig(t),r=new Set((e.match(/^\s*import .*$/gm)||[]).map(Jl).filter(Boolean)),i=s.split(` +`).filter(n=>{const o=Jl(n);return o===null||!r.has(o)?!0:!ng.test(n)}).join(` +`).replace(/^\s*\/\/ Automatic FlutterFlow imports\s*$/m,"").replace(/^\s*\n+/,"");return e+i}const ag=new Set(["flutter","flutter_test","flutter_driver","flutter_localizations"]);function lg(t){let e="",s=0;for(;s{const r=s.name||s.package;if(!r||r==="flutter")return e;const i=s.versionRequired||s.required;return e[r]=i&&s.version||"",e},{})}function hg(t){const e=new Map,s=new Map,r=[];for(const i of t)e.has(i.fileName)?r.push(`Duplicate deploy file name "${i.fileName}" for artifacts "${e.get(i.fileName)}" and "${i.artifactId}".`):e.set(i.fileName,i.artifactId),s.has(i.path)?r.push(`Duplicate deploy path "${i.path}" for artifacts "${s.get(i.path)}" and "${i.artifactId}".`):s.set(i.path,i.artifactId);return r}function pg(t,e={}){const s=Array.isArray(t==null?void 0:t.artifacts)?t.artifacts:[],i=(e.selectedArtifactIds||(t==null?void 0:t.deployOrder)||s.map(p=>p.id)).map(p=>s.find(f=>f.id===p)).filter(Boolean),n=[...(t==null?void 0:t.warnings)||[]];let o=[];i.forEach(p=>{const f=dg(p),g=p.fixedCode||p.code||"",v=p.codeType||cg[p.artifactType]||Ne.OTHER;g.trim()||n.push(`${p.artifactName||p.id} has no generated code.`),o.push({artifactId:p.id,artifactName:p.artifactName,artifactType:p.artifactType,fileName:f,content:g,type:v,path:p.deployPath||ug(f,v),deployPath:p.deployPath||"",deployMode:"customCodeSync"})});const a="lib/flutter_flow/custom_functions.dart",l=o.map((p,f)=>({entry:p,index:f})).filter(({entry:p})=>p.type===Ne.FUNCTION&&p.path===a);if(l.length>1){const p=l[0],f={...p.entry,artifactId:l.map(({entry:v})=>v.artifactId).join("+"),artifactName:p.entry.artifactName,content:l.map(({entry:v})=>`// ${v.artifactId} ${v.content}`).join(` -`)},g=new Set(l.slice(1).map(({index:v})=>v));o=o.filter((v,_)=>!g.has(_)),o[p.index]=f}const u={...Kl(t==null?void 0:t.dependencies),...i.reduce((p,f)=>({...p,...Kl(f.dependencies)}),{})},c={};i.forEach(p=>{ld(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=lg(o);return{bundleId:(t==null?void 0:t.id)||"bundle-current",title:(t==null?void 0:t.title)||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:(t==null?void 0:t.relationships)||[],warnings:n,errors:h}}function ug(t){var e;return(e=String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/))==null?void 0:e[1]}function dg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function hg(t,e){const r=[dg(t),ug(e.content),e.artifactName].find(i=>/^[A-Z][A-Za-z0-9_]*$/.test(String(i||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function pg(t,e=new Map){const s=[];for(const[r,i]of t.entries())i.type!=="C"||e.has(i.path)||s.push({artifactId:i.artifactId||r,className:hg(r,i),content:i.content,fileName:r,path:i.path});return s}function fg(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const Jl={pass:0,warning:1,fail:2},gg=["manualActions"];function Be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ft(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` -`);if(s)return s}}return""}function et(t){return t==null?[]:Array.isArray(t)?t:[t]}function mg(t){const e=Be(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Ko(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function ho(...t){return t.filter(Boolean).reduce((e,s)=>Jl[s]>Jl[e]?s:e,"pass")}function cd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=Be(t),i=ft(r.message,r.title,r.issue,r.description,r.summary);return i?{severity:Ko(r.severity||r.status||r.level)||e,message:i,suggestion:ft(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function po(t,e="review"){const s=Be(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([i,n])=>et(s[i]).map(o=>cd(o,n,e)).filter(Boolean))}function vg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=Be(t),i=ft(r.title,r.action,r.step,r.message,r.name,r.description);return i?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:i,detail:ft(r.detail,r.instructions,r.description),location:ft(r.location,r.flutterFlowPath,r.path),timing:ft(r.timing,r.phase)||"unspecified",artifactId:s,source:ft(r.source)||"Code Review"}:null}function fo(t,e=null){const s=Be(t);return gg.flatMap(r=>et(s[r])).map((r,i)=>vg(r,i,e)).filter(Boolean)}function _g(t){let e=typeof t=="string"?co(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=Be(e);typeof s.content=="string"&&(e=co(s.content)||e);const r=Be(e),i=Be(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(i).length?i:r}}function yg(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const i=Be(r);return[i.id,i.fileName,i.artifactName,i.name].map(We).some(n=>n&&s.includes(n))})||null}function wg(t,e){var i,n;const r=et((n=(i=t==null?void 0:t.metadata)==null?void 0:i.compatibility)==null?void 0:n.deployHints).find(o=>We(o==null?void 0:o.artifactId)===We(e.id)||We(o==null?void 0:o.fileName)===We(e.fileName));return(r==null?void 0:r.pathHint)||""}function bg(t,e){return et(t==null?void 0:t.relationships).filter(s=>We(s==null?void 0:s.from)===We(e.id)||We(s==null?void 0:s.to)===We(e.id))}function Eg(t,e){var s,r;return et((r=(s=t==null?void 0:t.metadata)==null?void 0:s.compatibility)==null?void 0:r.findings).filter(i=>!(i!=null&&i.artifactId)||We(i.artifactId)===We(e.id)).map(i=>cd(i,"warning","Compatibility check")).filter(Boolean)}function Sg(t,e,s,r){const i=yg(e,s),n=Be((i==null?void 0:i.review)||i||s.review),o=Object.keys(n).length>0,a=[...po(n),...Eg(t,s)],l=fo(n,s.id),u=Ko(n.status||n.verdict||n.outcome||n.result),c=a.length?ho(...a.map(h=>h.severity)):null,d=ho(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?ft(n.summary,n.overview,n.assessment,n.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof n.fixedSource=="string"&&n.fixedSource.trim()?n.fixedSource.trim():null,pathHint:wg(t,s),relationships:bg(t,s)}}function xg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const i=s.length;if(i===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const n=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),i&&o.push(`${i} artifact${i===1?"":"s"}: ${n.pass} pass, ${n.warning} warn, ${n.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function kg({bundle:t,reviewResult:e}){var S;const s=Be(t),r=et(s.artifacts),{root:i,rawText:n}=_g(e),o=[i.bundleReview,i.overallReview,i.overall,i.bundleSummary,i.summaryReview,i.review].map(Be).find(k=>Object.keys(k).length)||{},a=et(i.artifacts||i.files||i.reviews),l=r.map((k,E)=>Sg(s,a,k,E)),u=po(i),d=[...po(o),...u],h=[...fo(o),...fo(i),...l.flatMap(k=>k.manualSteps)].filter((k,E,P)=>P.findIndex(B=>B.title===k.title&&B.artifactId===k.artifactId)===E),p=Ko(o.status||o.verdict||o.overallStatus||i.status||i.verdict||i.overallStatus||i.outcome),f=ho(p,...d.map(k=>k.severity),...l.map(k=>k.status)),g=o.score??i.score??i.overallScore??n,v=mg(g),_=ft(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,i.overallSummary,i.headline,i.summary,i.executiveSummary,i.overview,i.assessment,i.conclusion,n)||xg({status:f,score:v,artifactPresentations:l,manualSteps:h}),w=l.reduce((k,E)=>(k[E.status]+=1,k),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:v,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(k=>k.reviewComplete).length,total:l.length},deployOrder:et(s.deployOrder),relationships:et(s.relationships),warnings:et(s.warnings),compatibility:Be((S=s.metadata)==null?void 0:S.compatibility)}}function ud(t){if(typeof t=="string")return t;if(Array.isArray(t)){const e=t.map(s=>typeof s=="string"?s:s==null?void 0:s.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}function Yl(t,e){const s=`${t}${e}`.split(` -`),r=s.pop()??"",i=[];for(const n of s){const o=dd(n);o&&i.push(o)}return{events:i,buffer:r}}function Ig(t){const e=dd(t);return e?[e]:[]}function dd(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function Cg(t,e={}){var a;const{onPhase:s,onLog:r}=e;let i=null,n="";const o=l=>{if(l.event==="phase"){l.message&&s&&s(l.message);return}if(l.event==="log"){l.message&&r&&r(l.message);return}i=l};if((a=t.body)!=null&&a.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const h=Yl(n,u.decode(d,{stream:!0}));n=h.buffer,h.events.forEach(o)}}else{const l=Yl("",await t.text());n=l.buffer,l.events.forEach(o)}return Ig(n).forEach(o),i?{...i,success:i.success===!0||i.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const Fg=/^dependencies\s*:\s*(?:#.*)?$/,Pg=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function hd(t){const e=t.match(Pg);return e?e[1]??e[2]??e[3]:null}function Jo(t){const e=t.trim();return e===""||e.startsWith("#")}function Ai(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function pd(t,e){const s=t.findIndex(n=>e.test(n));if(s===-1)return null;let r=s,i=null;for(let n=s+1;n=0.0.0"}`}function Tg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const i=s.split(` -`),n=new Set(gd(s)),o=[],a=[];for(const[u,c]of r)n.has(u)?a.push(u):(o.push([u,c]),n.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=Yo(i);if(l){const u=o.map(([c,d])=>Zl(l.childIndent,c,d));i.splice(l.endIndex,0,...u)}else i.length>0&&i[i.length-1].trim()!==""&&i.push(""),i.push("dependencies:"),o.forEach(([u,c])=>{i.push(Zl(" ",u,c))});return{yaml:i.join(` -`),added:o.map(([u])=>u),alreadyPresent:a}}function $g(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const i=s.split(` -`),n=Zo(s),o=[],a=[];for(const[l,u]of r){const c=n.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat(Ai(i[c.lineIndex]));i[c.lineIndex]=`${d}${l}: ${md(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:i.join(` -`),overridden:o,skipped:a}}function vd(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),Yo(e.split(` -`))||s.push("pubspec.yaml missing dependencies section"),gd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Mg=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function yt(t){const e=String(t||"").trim().match(Mg);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Ng(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let s=0;s0)}function Lg(t){const e=yt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function Xo(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return yt(o)?{min:o,minInclusive:!0,max:Lg(o),maxInclusive:!1}:null}if(yt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let i=!1,n;for(;(n=r.exec(e))!==null;){const[,o,a]=n;if(!yt(a))return null;i=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return i?s:null}function Xl(t,e){const s=Xo(t);if(!s||!yt(e))return!1;if(s.min!==null){const r=pi(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=pi(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function Bg(t,e){const s=Xo(t);if(!s||!yt(e))return!1;if(s.max===null)return!0;const r=pi(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function rs(t){const e=Xo(t);return e?e.min:null}const Dg="https://pub.dev/api/packages/",jg=8e3;function Ug(t,e={}){var o;const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,i=Array.isArray(t==null?void 0:t.versions)?t.versions:[];let n=null;for(const a of i){const l=a==null?void 0:a.version;if(!l||a.retracted||Og(l))continue;const u=((o=a.pubspec)==null?void 0:o.environment)||{};s&&u.sdk&&!Xl(u.sdk,s)||r&&u.flutter&&!Xl(u.flutter,r)||(!n||pi(l,n)>0)&&(n=l)}return n?{version:n,constraint:`^${n}`}:null}async function Hg(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:i=fetch}=e;let n;try{const a=await i(`${Dg}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(jg)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};n=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=Ug(n,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function Wg(t,e={}){const s=await Promise.all(t.map(r=>Hg(r,e)));return new Map(s.map(({name:r,...i})=>[r,i]))}async function zg(t,e={},s={}){const{resolveVersions:r=Wg}=s,i=Object.entries(e).filter(([c])=>c&&c!=="flutter"),n=Rg(t),o={dartSdkFloor:rs(n.sdk),flutterSdkFloor:rs(n.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(i.length===0)return a;const l=Zo(t),u=[];for(const[c,d]of i){const h=l.get(c);if(!h){u.push(c);continue}const p=rs(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Bg(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h!=null&&h.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(rs(p)){a.additions[d]=`^${rs(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${(h==null?void 0:h.error)||"lookup failed"}). Using ^${rs(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${(h==null?void 0:h.error)||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const qg={"&":"&","<":"<",">":">",'"':""","'":"'"};function wt(t){return String(t??"").replace(/[&<>"']/g,e=>qg[e])}function j(t){return t?wt(t).replace(/\n/g,"
"):""}function kt(t){return wt(t).replace(/\r?\n/g," ")}function Vg(t,e={}){const s=t==null?void 0:t.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=(t==null?void 0:t.message)||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function Gg(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function Kg(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function Jg(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function Ql(t){return t=wt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function _d(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(i){console.warn("Syntax highlighting failed:",i);try{return s.highlight(r,{language:"json"}).value}catch{return wt(r)}}}function Ri(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
';const i=String(t??"").split(` -`);let n=!1,o="";for(const a of i){if(a.startsWith("```")){if(n){const l=Jg(o),u=_d(o.trim(),l,s);r+=`
+`)},g=new Set(l.slice(1).map(({index:v})=>v));o=o.filter((v,_)=>!g.has(_)),o[p.index]=f}const u={...Yl(t==null?void 0:t.dependencies),...i.reduce((p,f)=>({...p,...Yl(f.dependencies)}),{})},c={};i.forEach(p=>{dd(p.code||"").forEach(f=>{f in u||(c[f]="")})});const d={...c,...u},h=hg(o);return{bundleId:(t==null?void 0:t.id)||"bundle-current",title:(t==null?void 0:t.title)||"Generated artifact bundle",fileEntries:o,dependencies:d,relationships:(t==null?void 0:t.relationships)||[],warnings:n,errors:h}}function fg(t){var e;return(e=String(t||"").match(/\bclass\s+([A-Z][A-Za-z0-9_]*)\b/))==null?void 0:e[1]}function gg(t){return String(t||"").split("/").pop().replace(/\.dart$/,"").split(/[^A-Za-z0-9]+/).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function mg(t,e){const r=[gg(t),fg(e.content),e.artifactName].find(i=>/^[A-Z][A-Za-z0-9_]*$/.test(String(i||"")));if(!r)throw new Error(`Cannot derive a FlutterFlow custom class name for ${t}.`);return r}function vg(t,e=new Map){const s=[];for(const[r,i]of t.entries())i.type!=="C"||e.has(i.path)||s.push({artifactId:i.artifactId||r,className:mg(r,i),content:i.content,fileName:r,path:i.path});return s}function _g(t,e){const s=new Set(e.map(r=>r.path));return new Map(Array.from(t.entries()).filter(([,r])=>!s.has(r.path)))}const Zl={pass:0,warning:1,fail:2},yg=["manualActions"];function Be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ft(...t){for(const e of t){if(typeof e=="string"&&e.trim())return e.trim();if(Array.isArray(e)&&e.length>0){const s=e.filter(r=>typeof r=="string").join(` +`);if(s)return s}}return""}function et(t){return t==null?[]:Array.isArray(t)?t:[t]}function wg(t){const e=Be(t).value??t;if(e==null||typeof e=="string"&&e.trim()==="")return null;const s=Number(e);if(Number.isFinite(s))return s;const r=String(t||"").match(/\bscore\b[^\d]{0,12}(\d{1,3})(?:\s*\/\s*100)?/i);return r?Number(r[1]):null}function We(t){return String(t||"").trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Yo(t){const e=String(t||"").toLowerCase();return/(fail|error|critical|block|reject|invalid)/.test(e)?"fail":/(warn|attention|manual|partial|incomplete|concern)/.test(e)?"warning":/(pass|success|ready|approve|valid|clean|info|notice)/.test(e)?"pass":null}function po(...t){return t.filter(Boolean).reduce((e,s)=>Zl[s]>Zl[e]?s:e,"pass")}function hd(t,e="warning",s="review"){if(typeof t=="string")return{severity:e,message:t,suggestion:"",source:s};const r=Be(t),i=ft(r.message,r.title,r.issue,r.description,r.summary);return i?{severity:Yo(r.severity||r.status||r.level)||e,message:i,suggestion:ft(r.suggestion,r.fix,r.recommendation,r.action),source:r.source||s}:null}function fo(t,e="review"){const s=Be(t);return[["findings","warning"],["issues","warning"],["criticalIssues","fail"],["errors","fail"],["warnings","warning"],["recommendations","warning"],["requiredFixes","fail"],["suggestions","warning"]].flatMap(([i,n])=>et(s[i]).map(o=>hd(o,n,e)).filter(Boolean))}function bg(t,e,s=null){if(typeof t=="string")return{id:`${s||"bundle"}-manual-${e+1}`,title:t,detail:"",location:"",timing:"unspecified",artifactId:s,source:"Code Review"};const r=Be(t),i=ft(r.title,r.action,r.step,r.message,r.name,r.description);return i?{id:r.id||`${s||"bundle"}-manual-${e+1}`,title:i,detail:ft(r.detail,r.instructions,r.description),location:ft(r.location,r.flutterFlowPath,r.path),timing:ft(r.timing,r.phase)||"unspecified",artifactId:s,source:ft(r.source)||"Code Review"}:null}function go(t,e=null){const s=Be(t);return yg.flatMap(r=>et(s[r])).map((r,i)=>bg(r,i,e)).filter(Boolean)}function Eg(t){let e=typeof t=="string"?uo(t):t;if(!e&&typeof t=="string")return{rawText:t,root:{}};const s=Be(e);typeof s.content=="string"&&(e=uo(s.content)||e);const r=Be(e),i=Be(r.reviewResult||r.codeReview||r.result);return{rawText:"",root:Object.keys(i).length?i:r}}function Sg(t,e){const s=[e.id,e.fileName,e.artifactName].map(We);return t.find(r=>{const i=Be(r);return[i.id,i.fileName,i.artifactName,i.name].map(We).some(n=>n&&s.includes(n))})||null}function xg(t,e){var i,n;const r=et((n=(i=t==null?void 0:t.metadata)==null?void 0:i.compatibility)==null?void 0:n.deployHints).find(o=>We(o==null?void 0:o.artifactId)===We(e.id)||We(o==null?void 0:o.fileName)===We(e.fileName));return(r==null?void 0:r.pathHint)||""}function kg(t,e){return et(t==null?void 0:t.relationships).filter(s=>We(s==null?void 0:s.from)===We(e.id)||We(s==null?void 0:s.to)===We(e.id))}function Ig(t,e){var s,r;return et((r=(s=t==null?void 0:t.metadata)==null?void 0:s.compatibility)==null?void 0:r.findings).filter(i=>!(i!=null&&i.artifactId)||We(i.artifactId)===We(e.id)).map(i=>hd(i,"warning","Compatibility check")).filter(Boolean)}function Cg(t,e,s,r){const i=Sg(e,s),n=Be((i==null?void 0:i.review)||i||s.review),o=Object.keys(n).length>0,a=[...fo(n),...Ig(t,s)],l=go(n,s.id),u=Yo(n.status||n.verdict||n.outcome||n.result),c=a.length?po(...a.map(h=>h.severity)):null,d=po(u,c,o?null:"warning");return{...s,index:r,status:d,statusReason:o?ft(n.summary,n.overview,n.assessment,n.conclusion)||(a.length?`${a.length} review finding${a.length===1?"":"s"}`:"No file-level findings"):"No file-level verdict was returned",reviewComplete:o,findings:a,manualSteps:l,fixedSource:typeof n.fixedSource=="string"&&n.fixedSource.trim()?n.fixedSource.trim():null,pathHint:xg(t,s),relationships:kg(t,s)}}function Fg({status:t,score:e,artifactPresentations:s,manualSteps:r}){const i=s.length;if(i===0&&r.length===0)return e==null?"Code review returned no overall summary and no score.":`Reviewed bundle with score ${e}/100.`;const n=s.reduce((a,l)=>(a[l.status]+=1,a),{pass:0,warning:0,fail:0}),o=[];return t&&o.push(`Overall verdict: ${t}.`),i&&o.push(`${i} artifact${i===1?"":"s"}: ${n.pass} pass, ${n.warning} warn, ${n.fail} fail.`),r.length&&o.push(`Do before deploy: ${r.map(a=>a.title).join("; ")}.`),e==null&&o.push("No numeric score (0-100) was returned."),o.join(" ")}function Pg({bundle:t,reviewResult:e}){var S;const s=Be(t),r=et(s.artifacts),{root:i,rawText:n}=Eg(e),o=[i.bundleReview,i.overallReview,i.overall,i.bundleSummary,i.summaryReview,i.review].map(Be).find(k=>Object.keys(k).length)||{},a=et(i.artifacts||i.files||i.reviews),l=r.map((k,x)=>Cg(s,a,k,x)),u=fo(i),d=[...fo(o),...u],h=[...go(o),...go(i),...l.flatMap(k=>k.manualSteps)].filter((k,x,P)=>P.findIndex(M=>M.title===k.title&&M.artifactId===k.artifactId)===x),p=Yo(o.status||o.verdict||o.overallStatus||i.status||i.verdict||i.overallStatus||i.outcome),f=po(p,...d.map(k=>k.severity),...l.map(k=>k.status)),g=o.score??i.score??i.overallScore??n,v=wg(g),_=ft(o.headline,o.summary,o.executiveSummary,o.overview,o.assessment,o.conclusion,i.overallSummary,i.headline,i.summary,i.executiveSummary,i.overview,i.assessment,i.conclusion,n)||Fg({status:f,score:v,artifactPresentations:l,manualSteps:h}),w=l.reduce((k,x)=>(k[x.status]+=1,k),{pass:0,warning:0,fail:0});return{title:s.title||"Generated artifact bundle",description:s.description||"",status:f,score:v,summary:_,findings:d,manualSteps:h,artifacts:l,counts:w,reviewCoverage:{reviewed:l.filter(k=>k.reviewComplete).length,total:l.length},deployOrder:et(s.deployOrder),relationships:et(s.relationships),warnings:et(s.warnings),compatibility:Be((S=s.metadata)==null?void 0:S.compatibility)}}const Ag=/^\s*```/,$g=/^\uFEFF/;function Cr(t){let e=0,s=t.length;for(;ee&&!t[s-1].trim();)s--;return t.slice(e,s).join(` +`)}function Rg(t){const e=String(t??"").replace($g,"");if(!e.trim())return"";const s=e.split(` +`),r=[];for(let o=0;o=a.length?l:a}const i=[];for(let o=0;o+1a+1&&i.push(Cr(s.slice(a+1,l)))}const n=i.filter(o=>o.length>0);return n.length===0?"":n.join(` + +`)}function Tg(t){return String(t??"").replace(/\/\*[\s\S]*?\*\//g," ").replace(/\/\/[^\n]*/g,"").replace(/'''[\s\S]*?'''/g,'""').replace(/"""[\s\S]*?"""/g,'""').replace(/'(?:\\.|[^'\\\n])*'/g,'""').replace(/"(?:\\.|[^"\\\n])*"/g,'""')}function pd(t){const e=Tg(t);return Array.from(e.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g),s=>s[1])}function fd(t){return`${ud(t)}.dart`}function Ng(t){return Ko(t,"W")}const Xl={"(":")","[":"]","{":"}"},Mg={")":"(","]":"[","}":"{"},Og=/[A-Za-z0-9_$]/;function Lg(t){const e=String(t??""),s=[{kind:"code",opener:null,openedLine:0}];let r=1,i=0;for(;i0?e[i-1]:"",c=i>1?e[i-2]:"",d=(u==="r"||u==="R")&&!Og.test(c);s.push({kind:"string",quote:o,triple:l,raw:d}),i+=l?3:1;continue}if(Xl[o]){s.push({kind:"code",opener:o,openedLine:r}),i++;continue}if(Mg[o]){if(a.interpolation&&o==="}"){s.pop(),i++;continue}if(a.opener&&Xl[a.opener]===o){s.pop(),i++;continue}return a.opener?`line ${r}: "${o}" closes nothing - "${a.opener}" opened on line ${a.openedLine} is still open`:`line ${r}: unexpected "${o}" with no matching opener`}o===` +`&&r++,i++}const n=s[s.length-1];if(n.kind==="code"&&!n.opener&&!n.interpolation)return null;if(n.kind==="string")return`unclosed ${n.triple?"triple-quoted ":""}string starting on line ${r} was never closed`;if(n.kind==="block-comment")return"unterminated /* comment";if(n.kind==="line-comment")return null;if(n.interpolation){const o=s.findLast(l=>l.opener);return`unclosed "\${" expression${o?` opened on line ${o.openedLine}`:""} was never closed`}return`"${n.opener}" opened on line ${n.openedLine} is never closed`}function gd(t){if(typeof t=="string")return t;if(Array.isArray(t)){const e=t.map(s=>typeof s=="string"?s:s==null?void 0:s.errorMessage).filter(Boolean);return e.length>0?e.join("; "):JSON.stringify(t)}return t&&typeof t=="object"?t.errorMessage||JSON.stringify(t):String(t??"")}function Ql(t,e){const s=`${t}${e}`.split(` +`),r=s.pop()??"",i=[];for(const n of s){const o=md(n);o&&i.push(o)}return{events:i,buffer:r}}function Bg(t){const e=md(t);return e?[e]:[]}function md(t){const e=t.trim();if(!e)return null;try{const s=JSON.parse(e);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}async function Dg(t,e={}){var a;const{onPhase:s,onLog:r}=e;let i=null,n="";const o=l=>{if(l.event==="phase"){l.message&&s&&s(l.message);return}if(l.event==="log"){l.message&&r&&r(l.message);return}i=l};if((a=t.body)!=null&&a.getReader){const l=t.body.getReader(),u=new TextDecoder;for(;;){const{done:c,value:d}=await l.read();if(c)break;const h=Ql(n,u.decode(d,{stream:!0}));n=h.buffer,h.events.forEach(o)}}else{const l=Ql("",await t.text());n=l.buffer,l.events.forEach(o)}return Bg(n).forEach(o),i?{...i,success:i.success===!0||i.success===void 0&&t.ok}:{success:!1,error:t.ok?"The FlutterFlow deploy runner closed the connection before it finished.":`FlutterFlow custom class provisioning failed (HTTP ${t.status}).`}}const jg=/^dependencies\s*:\s*(?:#.*)?$/,Ug=/^(?:"([^"]+)"|'([^']+)'|([A-Za-z_][A-Za-z0-9_-]*))\s*:/;function vd(t){const e=t.match(Ug);return e?e[1]??e[2]??e[3]:null}function Zo(t){const e=t.trim();return e===""||e.startsWith("#")}function $i(t){const e=t.match(/^(\s*)/);return e?e[1].length:0}function _d(t,e){const s=t.findIndex(n=>e.test(n));if(s===-1)return null;let r=s,i=null;for(let n=s+1;n=0.0.0"}`}function zg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([u])=>u&&u!=="flutter");if(r.length===0)return{yaml:s,added:[],alreadyPresent:[]};const i=s.split(` +`),n=new Set(wd(s)),o=[],a=[];for(const[u,c]of r)n.has(u)?a.push(u):(o.push([u,c]),n.add(u));if(o.length===0)return{yaml:s,added:[],alreadyPresent:a};const l=Xo(i);if(l){const u=o.map(([c,d])=>ec(l.childIndent,c,d));i.splice(l.endIndex,0,...u)}else i.length>0&&i[i.length-1].trim()!==""&&i.push(""),i.push("dependencies:"),o.forEach(([u,c])=>{i.push(ec(" ",u,c))});return{yaml:i.join(` +`),added:o.map(([u])=>u),alreadyPresent:a}}function qg(t,e={}){const s=String(t||""),r=Object.entries(e).filter(([l])=>l&&l!=="flutter");if(r.length===0)return{yaml:s,overridden:[],skipped:[]};const i=s.split(` +`),n=Qo(s),o=[],a=[];for(const[l,u]of r){const c=n.get(l);if(!c||!c.isScalar||!String(u||"").trim()){a.push(l);continue}const d=" ".repeat($i(i[c.lineIndex]));i[c.lineIndex]=`${d}${l}: ${bd(String(u).trim())}${c.comment}`,o.push({name:l,from:c.constraint,to:u})}return{yaml:i.join(` +`),overridden:o,skipped:a}}function Ed(t){const e=String(t||""),s=[];return e.trim()?(/^name:\s*\S+/m.test(e)||s.push("pubspec.yaml missing name field"),Xo(e.split(` +`))||s.push("pubspec.yaml missing dependencies section"),wd(e).includes("flutter")||s.push("pubspec.yaml missing Flutter SDK dependency"),{valid:s.length===0,errors:s}):(s.push("pubspec.yaml is empty"),{valid:!1,errors:s})}const Vg=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function yt(t){const e=String(t||"").trim().match(Vg);return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3]),prerelease:e[4]?e[4].split("."):[]}:null}function Gg(t,e){if(t.length===0&&e.length===0)return 0;if(t.length===0)return 1;if(e.length===0)return-1;for(let s=0;s0)}function Jg(t){const e=yt(t);return e?e.major>0?`${e.major+1}.0.0`:`0.${e.minor+1}.0`:null}function ea(t){let e=String(t??"").trim();if((e.startsWith("'")||e.startsWith('"'))&&(e=e.slice(1,-1).trim()),e===""||e==="any"||e==="*")return{min:null,minInclusive:!1,max:null,maxInclusive:!1};if(e.startsWith("^")){const o=e.slice(1).trim();return yt(o)?{min:o,minInclusive:!0,max:Jg(o),maxInclusive:!1}:null}if(yt(e))return{min:e,minInclusive:!0,max:e,maxInclusive:!0};const s={min:null,minInclusive:!1,max:null,maxInclusive:!1},r=/(>=|<=|>|<)\s*([0-9][0-9A-Za-z.+-]*)/g;let i=!1,n;for(;(n=r.exec(e))!==null;){const[,o,a]=n;if(!yt(a))return null;i=!0,o===">="||o===">"?(s.min=a,s.minInclusive=o===">="):(s.max=a,s.maxInclusive=o==="<=")}return i?s:null}function tc(t,e){const s=ea(t);if(!s||!yt(e))return!1;if(s.min!==null){const r=fi(e,s.min);if(r<0||r===0&&!s.minInclusive)return!1}if(s.max!==null){const r=fi(e,s.max);if(r>0||r===0&&!s.maxInclusive)return!1}return!0}function Yg(t,e){const s=ea(t);if(!s||!yt(e))return!1;if(s.max===null)return!0;const r=fi(s.max,e);return r>0?!0:r===0&&s.maxInclusive}function rs(t){const e=ea(t);return e?e.min:null}const Zg="https://pub.dev/api/packages/",Xg=8e3;function Qg(t,e={}){var o;const{dartSdkFloor:s=null,flutterSdkFloor:r=null}=e,i=Array.isArray(t==null?void 0:t.versions)?t.versions:[];let n=null;for(const a of i){const l=a==null?void 0:a.version;if(!l||a.retracted||Kg(l))continue;const u=((o=a.pubspec)==null?void 0:o.environment)||{};s&&u.sdk&&!tc(u.sdk,s)||r&&u.flutter&&!tc(u.flutter,r)||(!n||fi(l,n)>0)&&(n=l)}return n?{version:n,constraint:`^${n}`}:null}async function em(t,e={}){const{dartSdkFloor:s=null,flutterSdkFloor:r=null,fetchImpl:i=fetch}=e;let n;try{const a=await i(`${Zg}${encodeURIComponent(t)}`,{signal:AbortSignal.timeout(Xg)});if(!a.ok)return{name:t,constraint:null,version:null,error:a.status===404?`"${t}" was not found on pub.dev`:`pub.dev returned ${a.status} for "${t}"`};n=await a.json()}catch(a){return{name:t,constraint:null,version:null,error:`could not reach pub.dev for "${t}" (${a.message})`}}const o=Qg(n,{dartSdkFloor:s,flutterSdkFloor:r});return o?{name:t,...o,error:null}:{name:t,constraint:null,version:null,error:s?`no published "${t}" release supports Dart ${s}`:`no published "${t}" release could be read`}}async function tm(t,e={}){const s=await Promise.all(t.map(r=>em(r,e)));return new Map(s.map(({name:r,...i})=>[r,i]))}async function sm(t,e={},s={}){const{resolveVersions:r=tm}=s,i=Object.entries(e).filter(([c])=>c&&c!=="flutter"),n=Wg(t),o={dartSdkFloor:rs(n.sdk),flutterSdkFloor:rs(n.flutter)},a={additions:{},overrides:{},kept:[],warnings:[],sdk:o};if(i.length===0)return a;const l=Qo(t),u=[];for(const[c,d]of i){const h=l.get(c);if(!h){u.push(c);continue}const p=rs(d);if(!p){a.kept.push({name:c,constraint:h.constraint});continue}if(!h.isScalar){a.warnings.push(`"${c}" is declared in your project from a git, path, or SDK source, but the generated code needs at least ${p}. Left as-is — update it yourself if the build fails.`),a.kept.push({name:c,constraint:h.constraint});continue}if(Yg(h.constraint,p)){a.kept.push({name:c,constraint:h.constraint});continue}a.overrides[c]=`^${p}`,a.warnings.push(`"${c}" was pinned to ${h.constraint} in your project, which cannot resolve the ${p} the generated code needs. Raising it to ^${p} — this changes a dependency the rest of your app also uses.`)}if(u.length>0){const c=await r(u,o);for(const d of u){const h=c.get(d);if(h!=null&&h.constraint){a.additions[d]=h.constraint;continue}const p=e[d]||"";if(rs(p)){a.additions[d]=`^${rs(p)}`,a.warnings.push(`Could not confirm "${d}" version on pub.dev (${(h==null?void 0:h.error)||"lookup failed"}). Using ^${rs(p)} from the AI's recommendation — verify this is current.`);continue}a.additions[d]=">=0.0.0",a.warnings.push(`Could not determine a version for "${d}" (${(h==null?void 0:h.error)||"lookup failed"}) and the AI supplied none. Added with a wide-open >=0.0.0 constraint — pin a concrete version in FlutterFlow before deploying.`)}}return a}const rm={"&":"&","<":"<",">":">",'"':""","'":"'"};function wt(t){return String(t??"").replace(/[&<>"']/g,e=>rm[e])}function j(t){return t?wt(t).replace(/\n/g,"
"):""}function kt(t){return wt(t).replace(/\r?\n/g," ")}function im(t,e={}){const s=t==null?void 0:t.pipelineStep;if(s!=null&&e[s]!=null)return e[s];const r=(t==null?void 0:t.message)||"";return r.includes("Code Generator")?2:r.includes("Code Review")?3:1}function nm(t){const e={"Integration Audit Report":"📋","Critical Issues":"❌",Warnings:"⚠️",Recommendations:"✅","Overall Score":"📊"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📄"}function om(t){const e={critical:"❌",warning:"⚠️",recommendation:"✅",score:"📊",issue:"🔍",fix:"🔧"};for(const[s,r]of Object.entries(e))if(t.toLowerCase().includes(s.toLowerCase()))return r;return"📝"}function am(t){return t.includes("class ")&&t.includes("extends ")||t.includes("StatelessWidget")||t.includes("StatefulWidget")||t.includes("import 'package:flutter/")?"dart":t.includes("def ")||t.includes("import ")||t.includes("print(")?"python":t.includes("function ")||t.includes("const ")||t.includes("console.")?"javascript":"dart"}function ws(t){if(!t)return"";if(typeof t!="string")return String(t);const e=/```(?:\w+)?\n?([\s\S]*?)```/,s=t.match(e);return s?s[1].trim():t.trim()}function sc(t){return t=wt(t),t=t.replace(/\*\*(.*?)\*\*/g,'$1'),t=t.replace(/\*(.*?)\*/g,'$1'),t=t.replace(/`(.*?)`/g,'$1'),t=t.replace(/\b(FAIL|ERROR|CRITICAL)\b/g,'$1'),t=t.replace(/\b(WARN|WARNING)\b/g,'$1'),t=t.replace(/\b(PASS|SUCCESS|OK)\b/g,'$1'),t}function Sd(t,e="dart",s=globalThis.hljs){if(!t)return"";const r=ws(t);try{return s.highlight(r,{language:e}).value}catch(i){console.warn("Syntax highlighting failed:",i);try{return s.highlight(r,{language:"json"}).value}catch{return wt(r)}}}function Ri(t,e={}){const{highlighter:s=globalThis.hljs}=e;let r='
';const i=String(t??"").split(` +`);let n=!1,o="";for(const a of i){if(a.startsWith("```")){if(n){const l=am(o),u=Sd(o.trim(),l,s);r+=`
${u}
`,o="",n=!1}else n=!0;continue}if(n){o+=a+` `;continue}if(a.startsWith("# ")){const l=a.substring(2).trim();r+=`

- ${Gg(l)} + ${nm(l)} ${wt(l)}

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

- ${Kg(l)} + ${om(l)} ${wt(l)}

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

${Ql(a)}

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

${sc(a)}

`)}return r+="
",`
@@ -65,28 +75,28 @@ ${v.content}`).join(`
${r}
- `}const Yg="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",Zg="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",Xg="https://us.i.posthog.com";Xu.init(Zg,{api_host:Xg,person_profiles:"identified_only"});function Ht(t,e={}){try{Xu.capture(t,e)}catch(s){console.error("PostHog tracking failed",s)}}const Ke="https://4tgke4.buildship.run",yd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},fi="ccc_auth_session",ec=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const Qg=`${Ke}/service/runpipeline`,em="bs_user_id",tm=`${Ke}/authUserCheck`;let Or={userId:null,status:null,resolved:!1};const gi={free:2,professional:50,power:2e3},mi="ccc_subscription",tc=3,sm=new Set(["active","trialing","paid"]),nr="google/gemini-3.7-flash",Lr=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],rm={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Wt(t){return rm[t]||t}const im=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function wd(t){return im.has(t)}const go=4,Sn=8*1024*1024,nm="https://4tgke4.buildship.run/service/runpipeline-image";let Ft=[];function om(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function am(t){const e=new FormData;return e.append("file",t),(await fetch(nm,{method:"POST",body:e})).json()}function lm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function cm(t){var l;const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(u=>u.size>Sn);s.length&&ue(`Skipped ${s.length} image(s) over the ${(Sn/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(u=>u.size<=Sn);if(!r.length){t.target.value="";return}const i=go-Ft.length,o=r.slice(0,i).map(async u=>{const c=await om(u);if(!c)return null;let d="";try{d=lm(await am(u))}catch{d=""}return{dataUrl:c,name:u.name,url:d}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!wd((l=document.getElementById("code-generator-model"))==null?void 0:l.value))&&(Ft.push(...a),r.length>i&&ue(`You can attach up to ${go} images.`,"info"),Qo())}function um(t){Ft.splice(t,1),Qo()}function Qo(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ft.forEach((s,r)=>{const i=document.createElement("div");i.className="prompt-img-thumb",i.innerHTML=`Prompt image`,t.appendChild(i)}),e&&(e.textContent=Ft.length>=go?"Image limit reached":"Add images"))}function bd(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=wd(e==null?void 0:e.value);t.classList.toggle("hidden",!s),!s&&Ft.length&&(Ft=[],Qo())}const ds="ccc_usage",Ed="google/gemini-3.7-flash",Sd="google/gemini-3.7-flash",xn="google/gemini-3.7-flash",sc={professional:11,power:49},mo={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"},Br={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 Dr={...Br};async function dm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const i=r.rates,n={AUD:1},o=new Set([...Object.keys(Br),...Object.values(vo),...Object.values(mo)]);for(const a of o)a!=="AUD"&&(typeof i[a]=="number"&&i[a]>0?n[a]=i[a]:Br[a]&&(n[a]=Br[a]));Dr=n}catch{}finally{clearTimeout(e)}}const vo={"America/Sao_Paulo":"BRL","America/Fortaleza":"BRL","America/Recife":"BRL","America/Bahia":"BRL","America/Belem":"BRL","America/Manaus":"BRL","America/Cuiaba":"BRL","America/Campo_Grande":"BRL","America/Araguaina":"BRL","America/Noronha":"BRL","America/Rio_Branco":"BRL","America/Porto_Velho":"BRL","America/Boa_Vista":"BRL","America/Maceio":"BRL","America/Santarem":"BRL","America/Eirunepe":"BRL","Europe/London":"GBP","Europe/Paris":"EUR","Europe/Berlin":"EUR","Europe/Madrid":"EUR","Europe/Rome":"EUR","Europe/Amsterdam":"EUR","Europe/Brussels":"EUR","Europe/Vienna":"EUR","Europe/Lisbon":"EUR","Europe/Dublin":"EUR","Europe/Helsinki":"EUR","Europe/Athens":"EUR","Europe/Bucharest":"RON","Europe/Budapest":"HUF","Europe/Warsaw":"PLN","Europe/Prague":"CZK","Europe/Copenhagen":"DKK","Europe/Stockholm":"SEK","Europe/Oslo":"NOK","Europe/Zurich":"CHF","Europe/Istanbul":"TRY","Europe/Moscow":"RUB","Europe/Kiev":"UAH","Europe/Kyiv":"UAH","Asia/Tokyo":"JPY","Asia/Seoul":"KRW","Asia/Shanghai":"CNY","Asia/Taipei":"TWD","Asia/Hong_Kong":"HKD","Asia/Singapore":"SGD","Asia/Kolkata":"INR","Asia/Calcutta":"INR","Asia/Bangkok":"THB","Asia/Ho_Chi_Minh":"VND","Asia/Jakarta":"IDR","Asia/Kuala_Lumpur":"MYR","Asia/Dubai":"AED","Asia/Jerusalem":"ILS","Asia/Tel_Aviv":"ILS","Asia/Manila":"PHP","Pacific/Auckland":"NZD","Australia/Sydney":"AUD","Australia/Melbourne":"AUD","Australia/Brisbane":"AUD","Australia/Perth":"AUD","Australia/Adelaide":"AUD","Australia/Hobart":"AUD","Australia/Darwin":"AUD","Australia/Lord_Howe":"AUD","America/Toronto":"CAD","America/Vancouver":"CAD","America/Edmonton":"CAD","America/Winnipeg":"CAD","America/Halifax":"CAD","America/St_Johns":"CAD","America/Regina":"CAD","America/New_York":"USD","America/Chicago":"USD","America/Denver":"USD","America/Los_Angeles":"USD","America/Phoenix":"USD","America/Anchorage":"USD","Pacific/Honolulu":"USD","America/Mexico_City":"MXN","America/Cancun":"MXN","America/Tijuana":"MXN","America/Argentina/Buenos_Aires":"ARS","America/Santiago":"CLP","America/Bogota":"COP","America/Lima":"PEN","Africa/Johannesburg":"ZAR"};function xd(){try{const n=Intl.DateTimeFormat().resolvedOptions().timeZone;if(n&&vo[n])return vo[n]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=mo[e];if(s)return s;const r=e.split("_")[0],i=mo[r];return i||"USD"}function rc(t,e){const s=Dr[e]??Dr.USD,r=t*s,i=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:i>=100||i%1===0?0:2}).format(i)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*Dr.USD)}}const tt="ccc_api_key_",vt="ccc_session_api_key_",it="ccc_encryption_key",or="ccc_encryption_key_scope",hm="ccc_keystore",vi="keys",ar="ccc_encryption_key_version";let _o=null,_i=null,lr=!1,yi=!1,ic=!1;class wi extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function nc(){if(ic)return;ic=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function kd(){return localStorage.getItem(ar)||""}function yo(){var t;return((t=crypto.randomUUID)==null?void 0:t.call(crypto))||Cd(crypto.getRandomValues(new Uint8Array(16)))}function pm(){const t=kd();if(t)return t;const e=yo();return localStorage.setItem(ar,e),e}function Es(){_o=null,_i=null,lr=!1,yi=!1}window.addEventListener("storage",t=>{t.key===ar&&Es()});function fm(){return new Promise((t,e)=>{const s=indexedDB.open(hm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(vi)||r.createObjectStore(vi)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function ea(t,e){const s=await fm();return new Promise((r,i)=>{const n=s.transaction(vi,t);let o;try{o=e(n.objectStore(vi))}catch(l){s.close(),i(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>i(o.error),n.oncomplete=()=>{s.close(),r(a)},n.onerror=()=>{s.close(),i(n.error||new Error("Encryption key transaction failed."))},n.onabort=()=>{s.close(),i(n.error||new Error("Encryption key transaction aborted."))}})}function gm(t){var e;return t instanceof CryptoKey&&((e=t.algorithm)==null?void 0:e.name)==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function mm(){const t=await ea("readonly",e=>e.get(it));return gm(t)?t:null}async function Id(t){await ea("readwrite",e=>e.put(t,it))}async function vm(){Es();try{await ea("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function _m(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Id(e),sessionStorage.removeItem(it),sessionStorage.removeItem(or),localStorage.removeItem(tt+"salt"),e}async function oc(t){const e=sessionStorage.getItem(it);if(e)return yi=sessionStorage.getItem(or)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new wi;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(or,"session"),yi=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ym(t){if(sessionStorage.getItem(or)==="session"&&sessionStorage.getItem(it))return nc(),lr=!0,oc(t);try{const e=await mm();if(e)return e;const s=await _m();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await Id(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),nc(),lr=!0,oc(t)}}async function ta(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=pm();_i!==s&&Es();const r=_o||ym(e);_o=r,_i=s;try{return await r}catch(i){throw Es(),i}}async function wm(t){const e=await ta(),s=_i,r=new TextEncoder,i=crypto.getRandomValues(new Uint8Array(12)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},e,r.encode(t)),o=new Uint8Array(i.length+n.byteLength);return o.set(i),o.set(new Uint8Array(n),i.length),{ciphertext:Cd(o),keyVersion:s,sessionFallback:lr}}async function bm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ta({allowSessionFallbackCreation:!1});if(lr&&!s&&!yi)throw new wi;const i=Em(t),n=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof wi)throw r;return console.error("Decryption failed:",r),null}}function Cd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let cr="",bi="",Js=null,lc=0;async function sa(){sessionStorage.getItem(it)&&await ta(),cr=await Ee("flutterflow"),bi=await Ee("flutterflow_project_id"),Cm(),Yt()}function ra(){document.getElementById("api-keys-modal").classList.add("open"),na(),cr&&Rd(cr)}function Fd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(ia(),s.classList.add("open"))}let bt=1;function Pd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ti(){const t=Pd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===bt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const i=e.querySelector("div:first-child");i&&(i.classList.remove("bg-gray-400"),i.classList.add("bg-blue-500"),i.innerHTML=r)}else if(r0&&bt<=t&&(bt++,Ti())}function xm(){const t=document.getElementById("walkthrough-modal");t&&(bt=1,Ti(),t.classList.add("open"))}function km(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Ad(){if(q.isVerified&&Kt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(bt=1,Ti(),e.classList.add("open"))}}async function na(){const t=document.getElementById("flutterflow-api-key-input");cr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Im()}function Im(){cc("flutterflow","flutterflow-key-status"),cc("flutterflow_project_id","flutterflow-project-status")}function cc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),i=s.querySelector("span");os(t)?(r.className="key-status-dot configured",i.className="text-green-600",i.textContent="User key configured"):(r.className="key-status-dot missing",i.className="text-gray-500",i.textContent="Not configured")}function Yt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Cm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,i)=>{const n=s[i];n==="flutterflow"?os("flutterflow")&&os("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):os("flutterflow")||os("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)"):os(n)?(r.className="key-status-dot configured",r.title=n.charAt(0).toUpperCase()+n.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=n.charAt(0).toUpperCase()+n.slice(1)+" (Not configured)")}),Yt()}async function Fm(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await ac("flutterflow",t.value);const s=(e==null?void 0:e.value.trim())||"";if(s){if(!$i(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await ac("flutterflow_project_id",s)}await sa(),na();const r=document.querySelector("#api-keys-modal .bg-blue-500"),i=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=i,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Fd()},1e3)}async function Pm(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ar,yo()),Es(),localStorage.removeItem(tt+"flutterflow"),localStorage.removeItem(tt+"flutterflow_project_id"),sessionStorage.removeItem(vt+"flutterflow"),sessionStorage.removeItem(vt+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(or),localStorage.removeItem(tt+"salt"),await vm(),localStorage.setItem(ar,yo()),localStorage.removeItem(tt+"flutterflow"),localStorage.removeItem(tt+"flutterflow_project_id"),sessionStorage.removeItem(vt+"flutterflow"),sessionStorage.removeItem(vt+"flutterflow_project_id"),await sa();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),na()}function $i(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Am(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function Rm(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;Am("flutterflow-api-key-input",s)}),t.addEventListener("blur",Tm(async e=>{const s=e.target.value.trim();s&&await Rd(s)},500)))}function Tm(t,e){let s;return function(...i){const n=()=>{clearTimeout(s),t(...i)};clearTimeout(s),s=setTimeout(n,e)}}async function Rd(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const i=await new dr(t,"").listProjects();if(!i||i.length===0){e.innerHTML='';return}e.innerHTML='',i.forEach(n=>{const o=document.createElement("option");o.value=n.id||n.projectId||"",o.textContent=n.name||n.projectName||`Project ${n.id}`,e.appendChild(o)}),bi&&(e.value=bi)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function $m(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` + `}const lm="https://ccc-ffai-runner-y5cyj3473a-uw.a.run.app/deployCustomClasses",cm="phc_KoqpBJCIiWMW5I6HKBM092DVXZbMmE4KkPHqI518pF3",um="https://us.i.posthog.com";td.init(cm,{api_host:um,person_profiles:"identified_only"});function Ht(t,e={}){try{td.capture(t,e)}catch(s){console.error("PostHog tracking failed",s)}}const Ke="https://4tgke4.buildship.run",xd={professional:"price_1T2ldCKszA2slvDXatdeCpbI",power:"price_1T2le9KszA2slvDXR4mPvw7M"},gi="ccc_auth_session",rc=new WeakSet;let q={email:null,sessionToken:null,isVerified:!1};function bs(t={}){return{tier:"free",status:"none",periodEnd:null,isLoading:!1,isResolved:!1,error:null,...t}}let fe=bs({isResolved:!0});const dm=`${Ke}/service/runpipeline`,hm="bs_user_id",pm=`${Ke}/authUserCheck`;let Lr={userId:null,status:null,resolved:!1};const mi={free:2,professional:50,power:2e3},vi="ccc_subscription",ic=3,fm=new Set(["active","trialing","paid"]),nr="google/gemini-3.7-flash",Br=["anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta","openrouter/free","openrouter/deepseek/deepseek-v4-pro"],gm={"google/gemini-3.7-flash":"Gemini 3.7 Flash","anthropic/claude-opus-5":"Claude Opus 5","openai/gpt-5.6-sol":"GPT-5.6 Sol","z-ai/glm-5.2":"GLM 5.2","moonshotai/kimi-k3":"Kimi K3","openrouter/auto-beta":"OpenRouter: Auto Router","openrouter/free":"OpenRouter: Free Models","openrouter/deepseek/deepseek-v4-pro":"DeepSeek v4 Pro"};function Wt(t){return gm[t]||t}const mm=new Set(["google/gemini-3.7-flash","anthropic/claude-opus-5","openai/gpt-5.6-sol","z-ai/glm-5.2","moonshotai/kimi-k3","openrouter/auto-beta"]);function kd(t){return mm.has(t)}const mo=4,xn=8*1024*1024,vm="https://4tgke4.buildship.run/service/runpipeline-image";let Ft=[];function _m(t){return new Promise(e=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=()=>e(null),s.readAsDataURL(t)})}async function ym(t){const e=new FormData;return e.append("file",t),(await fetch(vm,{method:"POST",body:e})).json()}function wm(t){if(Array.isArray(t)){const e=t[0];if(e&&typeof e=="object")for(const s of Object.keys(e)){if(s==="item"||s==="index")continue;const r=e[s];if(r&&typeof r=="object"){if(typeof r.file=="string")return r.file;if(typeof r.url=="string")return r.url}if(typeof r=="string")return r}return""}return typeof t=="string"?t:t&&typeof t=="object"&&(t.url||t.fileUrl||t.file_url||t.downloadUrl||t.imageUrl||t.image_url||t.file)||""}async function bm(t){var l;const e=Array.from(t.target.files||[]);if(!e.length)return;const s=e.filter(u=>u.size>xn);s.length&&ue(`Skipped ${s.length} image(s) over the ${(xn/1024/1024).toFixed(0)} MB limit.`,"warning");const r=e.filter(u=>u.size<=xn);if(!r.length){t.target.value="";return}const i=mo-Ft.length,o=r.slice(0,i).map(async u=>{const c=await _m(u);if(!c)return null;let d="";try{d=wm(await ym(u))}catch{d=""}return{dataUrl:c,name:u.name,url:d}}),a=(await Promise.all(o)).filter(Boolean);t.target.value="",!(a.length&&!kd((l=document.getElementById("code-generator-model"))==null?void 0:l.value))&&(Ft.push(...a),r.length>i&&ue(`You can attach up to ${mo} images.`,"info"),ta())}function Em(t){Ft.splice(t,1),ta()}function ta(){const t=document.getElementById("prompt-image-thumbnails"),e=document.getElementById("prompt-image-btn-label");t&&(t.innerHTML="",Ft.forEach((s,r)=>{const i=document.createElement("div");i.className="prompt-img-thumb",i.innerHTML=`Prompt image`,t.appendChild(i)}),e&&(e.textContent=Ft.length>=mo?"Image limit reached":"Add images"))}function Id(){const t=document.getElementById("prompt-image-upload");if(!t)return;const e=document.getElementById("code-generator-model"),s=kd(e==null?void 0:e.value);t.classList.toggle("hidden",!s),!s&&Ft.length&&(Ft=[],ta())}const ds="ccc_usage",Cd="google/gemini-3.7-flash",Fd="google/gemini-3.7-flash",kn="google/gemini-3.7-flash",nc={professional:11,power:49},vo={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"},Dr={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 jr={...Dr};async function Sm(){const t=new AbortController,e=setTimeout(()=>t.abort(),5e3);try{const s=await fetch("https://open.er-api.com/v6/latest/AUD",{signal:t.signal});if(!s.ok)return;const r=await s.json();if(r.result!=="success"||!r.rates)return;const i=r.rates,n={AUD:1},o=new Set([...Object.keys(Dr),...Object.values(_o),...Object.values(vo)]);for(const a of o)a!=="AUD"&&(typeof i[a]=="number"&&i[a]>0?n[a]=i[a]:Dr[a]&&(n[a]=Dr[a]));jr=n}catch{}finally{clearTimeout(e)}}const _o={"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 Pd(){try{const n=Intl.DateTimeFormat().resolvedOptions().timeZone;if(n&&_o[n])return _o[n]}catch{}const e=(navigator.language||"en-US").replace("-","_"),s=vo[e];if(s)return s;const r=e.split("_")[0],i=vo[r];return i||"USD"}function oc(t,e){const s=jr[e]??jr.USD,r=t*s,i=Math.round(r*100)/100;try{return new Intl.NumberFormat("en-US",{style:"currency",currency:e,minimumFractionDigits:0,maximumFractionDigits:i>=100||i%1===0?0:2}).format(i)}catch{return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:2}).format(t*jr.USD)}}const tt="ccc_api_key_",vt="ccc_session_api_key_",it="ccc_encryption_key",or="ccc_encryption_key_scope",xm="ccc_keystore",_i="keys",ar="ccc_encryption_key_version";let yo=null,yi=null,lr=!1,wi=!1,ac=!1;class bi extends Error{constructor(){super("Secure browser key storage is unavailable."),this.name="CredentialStorageUnavailableError"}}function lc(){if(ac)return;ac=!0;const t="Secure browser key storage is unavailable. Existing credentials were left untouched; new credentials will be available only in this tab session.";console.warn(t),document.body&&ue(t,"warning")}function Ad(){return localStorage.getItem(ar)||""}function wo(){var t;return((t=crypto.randomUUID)==null?void 0:t.call(crypto))||Rd(crypto.getRandomValues(new Uint8Array(16)))}function km(){const t=Ad();if(t)return t;const e=wo();return localStorage.setItem(ar,e),e}function Es(){yo=null,yi=null,lr=!1,wi=!1}window.addEventListener("storage",t=>{t.key===ar&&Es()});function Im(){return new Promise((t,e)=>{const s=indexedDB.open(xm,1);s.onupgradeneeded=()=>{const r=s.result;r.objectStoreNames.contains(_i)||r.createObjectStore(_i)},s.onsuccess=()=>t(s.result),s.onerror=()=>e(s.error)})}async function sa(t,e){const s=await Im();return new Promise((r,i)=>{const n=s.transaction(_i,t);let o;try{o=e(n.objectStore(_i))}catch(l){s.close(),i(l);return}let a;o.onsuccess=()=>{a=o.result},o.onerror=()=>i(o.error),n.oncomplete=()=>{s.close(),r(a)},n.onerror=()=>{s.close(),i(n.error||new Error("Encryption key transaction failed."))},n.onabort=()=>{s.close(),i(n.error||new Error("Encryption key transaction aborted."))}})}function Cm(t){var e;return t instanceof CryptoKey&&((e=t.algorithm)==null?void 0:e.name)==="AES-GCM"&&t.extractable===!1&&t.usages.includes("encrypt")&&t.usages.includes("decrypt")}async function Fm(){const t=await sa("readonly",e=>e.get(it));return Cm(t)?t:null}async function $d(t){await sa("readwrite",e=>e.put(t,it))}async function Pm(){Es();try{await sa("readwrite",t=>t.delete(it))}catch(t){console.warn("Could not delete the stored encryption key:",t)}}async function Am(){const t=sessionStorage.getItem(it);if(!t)return null;const e=await crypto.subtle.importKey("jwk",JSON.parse(t),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await $d(e),sessionStorage.removeItem(it),sessionStorage.removeItem(or),localStorage.removeItem(tt+"salt"),e}async function cc(t){const e=sessionStorage.getItem(it);if(e)return wi=sessionStorage.getItem(or)!=="session",crypto.subtle.importKey("jwk",JSON.parse(e),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);if(!t)throw new bi;const s=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),r=await crypto.subtle.exportKey("jwk",s);return sessionStorage.setItem(it,JSON.stringify(r)),sessionStorage.setItem(or,"session"),wi=!1,crypto.subtle.importKey("jwk",r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function $m(t){if(sessionStorage.getItem(or)==="session"&&sessionStorage.getItem(it))return lc(),lr=!0,cc(t);try{const e=await Fm();if(e)return e;const s=await Am();if(s)return s;const r=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]);return await $d(r),r}catch(e){return console.warn("IndexedDB encryption-key storage failed:",e),lc(),lr=!0,cc(t)}}async function ra(t={}){const{allowSessionFallbackCreation:e=!0}=t,s=km();yi!==s&&Es();const r=yo||$m(e);yo=r,yi=s;try{return await r}catch(i){throw Es(),i}}async function Rm(t){const e=await ra(),s=yi,r=new TextEncoder,i=crypto.getRandomValues(new Uint8Array(12)),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:i},e,r.encode(t)),o=new Uint8Array(i.length+n.byteLength);return o.set(i),o.set(new Uint8Array(n),i.length),{ciphertext:Rd(o),keyVersion:s,sessionFallback:lr}}async function Tm(t,e={}){const{isSessionCredential:s=!1}=e;try{const r=await ra({allowSessionFallbackCreation:!1});if(lr&&!s&&!wi)throw new bi;const i=Nm(t),n=i.slice(0,12),o=i.slice(12),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},r,o);return new TextDecoder().decode(a)}catch(r){if(r instanceof bi)throw r;return console.error("Decryption failed:",r),null}}function Rd(t){const e=new Uint8Array(t);let s="";for(let r=0;r0}let cr="",Ei="",Js=null,dc=0;async function ia(){sessionStorage.getItem(it)&&await ra(),cr=await Ee("flutterflow"),Ei=await Ee("flutterflow_project_id"),Dm(),Yt()}function na(){document.getElementById("api-keys-modal").classList.add("open"),aa(),cr&&Od(cr)}function Td(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("api-keys-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-modal");s&&(oa(),s.classList.add("open"))}let bt=1;function Nd(){const t=document.querySelector(".wt-steps");return t?Array.from(t.querySelectorAll(".wt-step-card")):[]}function Ti(){const t=Nd();t.length&&t.forEach((e,s)=>{const r=s+1;if(r===bt){e.classList.remove("opacity-60","bg-gray-50","border-gray-200"),e.classList.add("bg-blue-50","border-blue-200");const i=e.querySelector("div:first-child");i&&(i.classList.remove("bg-gray-400"),i.classList.add("bg-blue-500"),i.innerHTML=r)}else if(r0&&bt<=t&&(bt++,Ti())}function Om(){const t=document.getElementById("walkthrough-modal");t&&(bt=1,Ti(),t.classList.add("open"))}function Lm(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("walkthrough-modal");e&&e.classList.remove("open");const s=document.getElementById("walkthrough-dont-show");s&&s.checked&&localStorage.setItem("hasSeenWalkthrough","true")}function Md(){if(q.isVerified&&Kt()&&fe.tier!=="free")return;if(!localStorage.getItem("hasSeenWalkthrough")){const e=document.getElementById("walkthrough-modal");e&&(bt=1,Ti(),e.classList.add("open"))}}async function aa(){const t=document.getElementById("flutterflow-api-key-input");cr?(t.value="",t.placeholder="Key saved (enter new to replace)"):t.placeholder="Enter your FlutterFlow API key",Bm()}function Bm(){hc("flutterflow","flutterflow-key-status"),hc("flutterflow_project_id","flutterflow-project-status")}function hc(t,e){const s=document.getElementById(e);if(!s)return;const r=s.querySelector(".key-status-dot"),i=s.querySelector("span");os(t)?(r.className="key-status-dot configured",i.className="text-green-600",i.textContent="User key configured"):(r.className="key-status-dot missing",i.className="text-gray-500",i.textContent="Not configured")}function Yt(){const t=y.step2Result&&y.step2Result.length>0,e=document.getElementById("btn-deploy-to-ff"),s=document.getElementById("btn-run-pipeline");s&&s.classList.remove("hidden"),e&&e.classList.toggle("hidden",!t)}function Dm(){const t=document.getElementById("api-keys-status");if(!t)return;const e=t.querySelectorAll(".key-status-dot"),s=["flutterflow"];e.forEach((r,i)=>{const n=s[i];n==="flutterflow"?os("flutterflow")&&os("flutterflow_project_id")?(r.className="key-status-dot configured",r.title="FlutterFlow (Fully configured)"):os("flutterflow")||os("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)"):os(n)?(r.className="key-status-dot configured",r.title=n.charAt(0).toUpperCase()+n.slice(1)+" (User key)"):(r.className="key-status-dot missing",r.title=n.charAt(0).toUpperCase()+n.slice(1)+" (Not configured)")}),Yt()}async function jm(){const t=document.getElementById("flutterflow-api-key-input"),e=document.getElementById("flutterflow-projects-select");t.value.trim()&&await uc("flutterflow",t.value);const s=(e==null?void 0:e.value.trim())||"";if(s){if(!Ni(s)){ue("The selected FlutterFlow project has an unexpected ID format.","error"),e.focus();return}await uc("flutterflow_project_id",s)}await ia(),aa();const r=document.querySelector("#api-keys-modal .bg-blue-500"),i=r.textContent;r.textContent="Saved!",r.classList.remove("bg-blue-500","hover:bg-blue-600"),r.classList.add("bg-green-500"),setTimeout(()=>{r.textContent=i,r.classList.remove("bg-green-500"),r.classList.add("bg-blue-500","hover:bg-blue-600"),Td()},1e3)}async function Um(){if(!confirm("Are you sure you want to clear all stored API keys?"))return;localStorage.setItem(ar,wo()),Es(),localStorage.removeItem(tt+"flutterflow"),localStorage.removeItem(tt+"flutterflow_project_id"),sessionStorage.removeItem(vt+"flutterflow"),sessionStorage.removeItem(vt+"flutterflow_project_id"),sessionStorage.removeItem(it),sessionStorage.removeItem(or),localStorage.removeItem(tt+"salt"),await Pm(),localStorage.setItem(ar,wo()),localStorage.removeItem(tt+"flutterflow"),localStorage.removeItem(tt+"flutterflow_project_id"),sessionStorage.removeItem(vt+"flutterflow"),sessionStorage.removeItem(vt+"flutterflow_project_id"),await ia();const t=document.getElementById("flutterflow-projects-select");t&&(t.innerHTML=''),aa()}function Ni(t){return!t||t.trim().length<5||t.includes(" ")?!1:/^[a-zA-Z0-9-]+$/.test(t)}function Hm(t,e){const s=document.getElementById(t);s&&(s.value?e?s.style.borderColor="#22c55e":s.style.borderColor="#ef4444":s.style.borderColor="")}function Wm(){const t=document.getElementById("flutterflow-api-key-input");t&&(t.addEventListener("input",e=>{const s=e.target.value.trim().length>0;Hm("flutterflow-api-key-input",s)}),t.addEventListener("blur",zm(async e=>{const s=e.target.value.trim();s&&await Od(s)},500)))}function zm(t,e){let s;return function(...i){const n=()=>{clearTimeout(s),t(...i)};clearTimeout(s),s=setTimeout(n,e)}}async function Od(t){const e=document.getElementById("flutterflow-projects-select"),s=document.getElementById("flutterflow-projects-error");if(!e){console.error("Projects dropdown element not found");return}e.innerHTML='',s&&s.classList.add("hidden");try{const i=await new dr(t,"").listProjects();if(!i||i.length===0){e.innerHTML='';return}e.innerHTML='',i.forEach(n=>{const o=document.createElement("option");o.value=n.id||n.projectId||"",o.textContent=n.name||n.projectName||`Project ${n.id}`,e.appendChild(o)}),Ei&&(e.value=Ei)}catch(r){console.error("Failed to fetch projects:",r),e.innerHTML='',s&&(s.textContent=`Failed to load projects: ${r.message}`,s.classList.remove("hidden"))}}function qm(t){const e=document.getElementById(t),r=e.nextElementSibling.querySelector("svg");e.type==="password"?(e.type="text",r.innerHTML=` `):(e.type="password",r.innerHTML=` - `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Mm(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Nm(){y.bundleSpec=rr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Mi(){var s,r,i,n;const t=di(y.bundleSpec);y.artifactBundle=rr(y.step2Result,{id:(s=y.bundleSpec)==null?void 0:s.id,title:(r=y.bundleSpec)==null?void 0:r.title,description:(i=y.bundleSpec)==null?void 0:i.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:(n=y.bundleSpec)==null?void 0:n.relationships,code:y.step2Result||""});const e=Qf(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(o=>o.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=di(y.artifactBundle).id}function Ni(){var r,i,n,o,a,l,u,c;const t=rr(y.step3Result,{id:(r=y.artifactBundle)==null?void 0:r.id,title:(i=y.artifactBundle)==null?void 0:i.title}),e=new Map(t.artifacts.map(d=>[d.id,d.review])),s=new Map(t.artifacts.filter(d=>{const h=d.review;return h&&typeof h.fixedSource=="string"&&h.fixedSource.trim()}).map(d=>[d.id,d.review.fixedSource.trim()]));y.bundleReview=rr({id:(n=y.artifactBundle)==null?void 0:n.id,title:(o=y.artifactBundle)==null?void 0:o.title,artifacts:((l=(a=y.artifactBundle)==null?void 0:a.artifacts)==null?void 0:l.map(d=>{const h=s.get(d.id)||null;return{...d,review:e.get(d.id)||d.review||y.step3Result||null,...h?{fixedCode:h}:{}}}))||[],relationships:(u=y.artifactBundle)==null?void 0:u.relationships,warnings:(c=y.artifactBundle)==null?void 0:c.warnings})}function Td(){const t=oa();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget"}}function oa(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t==null?void 0:t.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||di(t)}function aa(){return oa().code||y.step2Result||""}async function Om(){try{await sa()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const jr={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};class dr{constructor(e,s,r="main",i=jr.production){this.apiKey=e,this.baseUrl=i,this._projectId=s,this._branchName=r,this._endpoint=i}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){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 s=null;for(const i of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!n.ok){const l=await n.text();s=new Error(`Export failed: ${n.status} - ${l}`);continue}const o=await n.json(),a=((r=o==null?void 0:o.value)==null?void 0:r.project_zip)||(o==null?void 0:o.project_zip);if(!a){s=new Error("Export response did not include project source.");continue}return a}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const i=r.slice(0,r.length-12),n=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(i))return!1;const l=a.slice(i.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{n.set(a.slice(i.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:n}}async pushCodeWithRetry(e,s=3){var n,o,a;const r=[jr.production,jr.staging],i=Math.max(0,r.indexOf(this._endpoint));for(let l=0;lsetTimeout(f,1e3*(l+1)));continue}return d}catch(d){console.warn(`Push to ${c} failed: ${d.message}, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}async listProjects(e={}){const{page:s=1,limit:r=100}=e;console.log("Listing projects for API key via V2 endpoint");try{const i=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(!i.ok){const a=await i.text();throw new Error(`List projects failed: ${i.status} - ${a}`)}const n=await i.json();if(n.success&&typeof n.value=="string")try{const a=JSON.parse(n.value);if(a&&Array.isArray(a.entries))return a.entries.map(l=>{var u;return{id:l.id,name:((u=l.project)==null?void 0:u.name)||l.id}})}catch(a){console.error("Failed to parse stringified project value:",a)}const o=n.projects||n.items||n.entries||(Array.isArray(n)?n:[]);return Array.isArray(o)?o:[]}catch(i){throw console.error("Error listing projects:",i),i}}}async function la(t){const e=t.clone();let s;try{s=await t.json()}catch{const n=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:n||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${n}`)}if(!t.ok){let i=s.message||`HTTP ${t.status}`,n=new Map;if(s.errors)n=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(n=new Map(Object.entries(s)),i=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` -`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:i,errorMap:n}}const r=s.value?JSON.parse(s.value):{};return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function ca(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},$d=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Md=/extends\s+State<\w+>/;function Lm(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=$d.test(e),r=Md.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function Nd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ua(t,e=new Map){return Mf(t,e)}const wo=new Map;function Od(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Oi(t){wo.delete(Od(t))}async function da(t,e,s,r){const i=pg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e};console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const n=await fetch(Yg,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,stream:!0})}),o=await Cg(n,{onPhase:a=>be.setSubstatus(a),onLog:a=>console.log(`[custom class deploy] ${a}`)});if(!o.success){const a=o.details?` ${o.details}`:"";throw new Error(`${o.error||"FlutterFlow custom class provisioning failed."}${a}`)}return Oi(t),{remoteFiles:s,syncFileMap:fg(e,i)}}async function ha(t,e={}){const s=Od(t);let r=wo.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=vd(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);wo.set(s,r)}const i=await zg(r.pubspecYaml,e),n=$g(r.pubspecYaml,i.overrides),o=Tg(n.yaml,i.additions);return i.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${i.additions[a]||"any"}`).join(", "),i.sdk.dartSdkFloor?`(resolved for Dart ${i.sdk.dartSdkFloor})`:""),i.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:n.overridden,warnings:i.warnings,remoteFiles:r.files}}function Bm(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` -`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const i=t.content.match(/print\s*\(/g);return i&&i.length>3&&s.push(`Code contains ${i.length} print statements. Consider removing debug prints before committing.`),{canProceed:e.length===0,issues:e,warnings:s}}function Ld(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode"}=e;let i=t.trim();i.startsWith("```dart")?i=i.replace(/^```dart\n/,""):i.startsWith("```")&&(i=i.replace(/^```\n/,"")),i.endsWith("```")&&(i=i.replace(/\n```$/,""));let n=r;n.endsWith(".dart")||(n+=".dart");let o=U.CODE_FILE;switch(s){case"CustomAction":o=U.ACTION;break;case"CustomWidget":o=U.WIDGET;break;case"CustomFunction":o=U.FUNCTION,n="custom_functions.dart";break;case"CustomClass":case"CodeFile":o=U.CODE_FILE;break}let a="";return o===U.WIDGET?a=`// Automatic FlutterFlow imports + `)}let y={step1Result:null,step2Result:null,step3Result:null,bundleSpec:null,artifactBundle:null,bundleReview:null,selectedArtifactId:null,resultsViewMode:"summary",currentStep:0,isRunning:!1};function Vm(){y.step1Result=null,y.step2Result=null,y.step3Result=null,y.bundleSpec=null,y.artifactBundle=null,y.bundleReview=null,y.selectedArtifactId=null,y.resultsViewMode="summary"}function Gm(){y.bundleSpec=rr(y.step1Result,{artifactType:"CustomWidget",artifactName:"GeneratedWidget"})}function Mi(){var s,r,i,n;const t=hi(y.bundleSpec);y.artifactBundle=rr(y.step2Result,{id:(s=y.bundleSpec)==null?void 0:s.id,title:(r=y.bundleSpec)==null?void 0:r.title,description:(i=y.bundleSpec)==null?void 0:i.description,artifactType:t.artifactType,artifactName:t.artifactName,fileName:t.fileName,dependencies:t.dependencies,relationships:(n=y.bundleSpec)==null?void 0:n.relationships,code:y.step2Result||""});const e=rg(y.artifactBundle);y.artifactBundle={...y.artifactBundle,warnings:[...y.artifactBundle.warnings,...e.findings.map(o=>o.message)],metadata:{...y.artifactBundle.metadata,compatibility:e}},y.selectedArtifactId=hi(y.artifactBundle).id}function Oi(){var r,i,n,o,a,l,u,c;const t=rr(y.step3Result,{id:(r=y.artifactBundle)==null?void 0:r.id,title:(i=y.artifactBundle)==null?void 0:i.title}),e=new Map(t.artifacts.map(d=>[d.id,d.review])),s=new Map(t.artifacts.filter(d=>{const h=d.review;return h&&typeof h.fixedSource=="string"&&h.fixedSource.trim()}).map(d=>[d.id,d.review.fixedSource.trim()]));y.bundleReview=rr({id:(n=y.artifactBundle)==null?void 0:n.id,title:(o=y.artifactBundle)==null?void 0:o.title,artifacts:((l=(a=y.artifactBundle)==null?void 0:a.artifacts)==null?void 0:l.map(d=>{const h=s.get(d.id)||null;return{...d,review:e.get(d.id)||d.review||y.step3Result||null,...h?{fixedCode:h}:{}}}))||[],relationships:(u=y.artifactBundle)==null?void 0:u.relationships,warnings:(c=y.artifactBundle)==null?void 0:c.warnings})}function Ld(){const t=la();return{artifactType:t.artifactType||"CustomWidget",artifactName:t.artifactName||"GeneratedWidget",fileName:t.fileName||""}}function la(){const t=y.artifactBundle||y.bundleSpec||null;return(Array.isArray(t==null?void 0:t.artifacts)?t.artifacts:[]).find(s=>s.id===y.selectedArtifactId)||hi(t)}function ca(){return la().code||y.step2Result||""}async function Km(){try{await ia()}catch(t){return console.error("checkConnection: initializeApiKeys failed:",t),!1}return!0}const Ur={production:"https://api.flutterflow.io/v2/",staging:"https://api.flutterflow.io/v2-staging/"};class dr{constructor(e,s,r="main",i=Ur.production){this.apiKey=e,this.baseUrl=i,this._projectId=s,this._branchName=r,this._endpoint=i}get projectId(){return this._projectId}get branchName(){return this._branchName==="main"?"":this._branchName}async exportProjectZip(){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 s=null;for(const i of e)try{const n=await fetch(`${this.baseUrl}exportCode`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(i)});if(!n.ok){const l=await n.text();s=new Error(`Export failed: ${n.status} - ${l}`);continue}const o=await n.json(),a=((r=o==null?void 0:o.value)==null?void 0:r.project_zip)||(o==null?void 0:o.project_zip);if(!a){s=new Error("Export response did not include project source.");continue}return a}catch(n){s=n}throw s||new Error("Export failed for an unknown reason.")}async fetchProjectSource(){const e=await this.exportProjectZip(),s=await JSZip.loadAsync(e,{base64:!0}),r=Object.keys(s.files).filter(a=>!s.files[a].dir&&(a==="pubspec.yaml"||a.endsWith("/pubspec.yaml"))).sort((a,l)=>a.split("/").length-l.split("/").length)[0];if(!r)throw new Error("Export did not contain a pubspec.yaml.");const i=r.slice(0,r.length-12),n=new Map,o=Object.keys(s.files).filter(a=>{if(s.files[a].dir||!a.startsWith(i))return!1;const l=a.slice(i.length);return l==="lib/flutter_flow/custom_functions.dart"||l.startsWith("lib/custom_code/")&&l.endsWith(".dart")});return await Promise.all(o.map(async a=>{n.set(a.slice(i.length),await s.files[a].async("string"))})),{pubspecYaml:await s.files[r].async("string"),files:n}}async pushCodeWithRetry(e,s=3){var n,o,a;const r=[Ur.production,Ur.staging],i=Math.max(0,r.indexOf(this._endpoint));for(let l=0;lsetTimeout(f,1e3*(l+1)));continue}return d}catch(d){console.warn(`Push to ${c} failed: ${d.message}, trying next...`),await new Promise(h=>setTimeout(h,1e3*(l+1)))}}throw new Error("All API endpoints failed after retries")}async pushCode(e){return this.pushCodeWithRetry(e)}async listProjects(e={}){const{page:s=1,limit:r=100}=e;console.log("Listing projects for API key via V2 endpoint");try{const i=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(!i.ok){const a=await i.text();throw new Error(`List projects failed: ${i.status} - ${a}`)}const n=await i.json();if(n.success&&typeof n.value=="string")try{const a=JSON.parse(n.value);if(a&&Array.isArray(a.entries))return a.entries.map(l=>{var u;return{id:l.id,name:((u=l.project)==null?void 0:u.name)||l.id}})}catch(a){console.error("Failed to parse stringified project value:",a)}const o=n.projects||n.items||n.entries||(Array.isArray(n)?n:[]);return Array.isArray(o)?o:[]}catch(i){throw console.error("Error listing projects:",i),i}}}async function ua(t){const e=t.clone();let s;try{s=await t.json()}catch{const n=await e.text();if(!t.ok)return{success:!1,responseCode:t.status,errorMessage:n||`HTTP ${t.status}`,errorMap:new Map};throw new Error(`Invalid JSON response: ${n}`)}if(!t.ok){let i=s.message||`HTTP ${t.status}`,n=new Map;if(s.errors)n=new Map(Object.entries(s.errors));else if(!s.message&&typeof s=="object"){const o=Object.keys(s).filter(a=>a.endsWith(".dart")&&Array.isArray(s[a]));o.length>0&&(n=new Map(Object.entries(s)),i=o.flatMap(l=>s[l].map(u=>`${l}: ${u.errorMessage}`)).join(` +`)||`HTTP ${t.status}`)}return{success:!1,responseCode:t.status,errorMessage:i,errorMap:n}}let r={};if(s.value)try{r=typeof s.value=="string"?JSON.parse(s.value):s.value}catch(i){console.warn("Ignoring malformed push response value:",i)}return{success:!0,responseCode:t.status,errorMap:new Map(Object.entries(r))}}function da(t,e){return{401:"Authentication failed. Please check your FlutterFlow API key.",403:"Access denied. You may not have permission to modify this project.",404:"Project not found. Please check your Project ID.",409:"Conflict detected. The project may have been modified elsewhere.",422:"Validation failed: Invalid request format",429:"Rate limit exceeded. Please try again in a few minutes.",500:"FlutterFlow server error. Please try again later.",503:"FlutterFlow service temporarily unavailable."}[t]||`FlutterFlow API error: ${`HTTP ${t}`}`}const U={ACTION:"A",WIDGET:"W",FUNCTION:"F",CODE_FILE:"C",DEPENDENCIES:"D",OTHER:"O"},Bd=/class\s+\w+\s+extends\s+(?:StatelessWidget|StatefulWidget)\b/,Dd=/extends\s+State<\w+>/;function Jm(t,e=""){if(t==="pubspec.yaml")return U.DEPENDENCIES;if(!t.endsWith(".dart")||t.endsWith("index.dart"))return U.OTHER;if(t==="custom_functions.dart")return U.FUNCTION;if(e){const s=Bd.test(e),r=Dd.test(e);if(s||r)return U.WIDGET;if(/^\s*Future(?:<[^>]+>)?\s+\w+\s*\(/m.test(e))return U.ACTION;if(e.match(/^\s*(String|int|double|bool|List|Map|dynamic|void)\s+\w+\s*\(/m))return U.FUNCTION}return U.CODE_FILE}function jd(t,e){switch(e){case U.ACTION:return`lib/custom_code/actions/${t}`;case U.WIDGET:return`lib/custom_code/widgets/${t}`;case U.FUNCTION:return"lib/flutter_flow/custom_functions.dart";case U.CODE_FILE:return`lib/custom_code/${t}`;case U.DEPENDENCIES:return"pubspec.yaml";case U.OTHER:return`lib/custom_code/${t}`;default:return t}}async function ha(t,e=new Map){return Df(t,e)}const bo=new Map;function Ud(t){return`${t.baseUrl}|${t.projectId}|${t.branchName}`}function Li(t){bo.delete(Ud(t))}async function pa(t,e,s,r){const i=vg(e,s);if(i.length===0)return{remoteFiles:s,syncFileMap:e};console.log(`Provisioning ${i.length} new FlutterFlow custom code file(s) before sync.`),be.set("provision");const n=await fetch(lm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:t.apiKey,projectId:t.projectId,baseUrl:t.baseUrl,commitMessage:r,customClasses:i,stream:!0})}),o=await Dg(n,{onPhase:a=>be.setSubstatus(a),onLog:a=>console.log(`[custom class deploy] ${a}`)});if(!o.success){const a=o.details?` ${o.details}`:"";throw new Error(`${o.error||"FlutterFlow custom class provisioning failed."}${a}`)}return Li(t),{remoteFiles:s,syncFileMap:_g(e,i)}}async function fa(t,e={}){const s=Ud(t);let r=bo.get(s);if(r===void 0){try{r=await t.fetchProjectSource()}catch(l){throw new Error(`Could not read your project's pubspec.yaml (${l.message}). Deploy was stopped so your existing package dependencies aren't overwritten. Check your FlutterFlow API key and project, then try again.`)}const a=Ed(r.pubspecYaml);if(!a.valid)throw new Error(`Your project's pubspec.yaml could not be read reliably (${a.errors.join("; ")}). Deploy was stopped so your existing package dependencies aren't overwritten.`);bo.set(s,r)}const i=await sm(r.pubspecYaml,e),n=qg(r.pubspecYaml,i.overrides),o=zg(n.yaml,i.additions);return i.warnings.forEach(a=>console.warn(`[pubspec] ${a}`)),o.added.length>0&&console.log("Adding dependencies:",o.added.map(a=>`${a}: ${i.additions[a]||"any"}`).join(", "),i.sdk.dartSdkFloor?`(resolved for Dart ${i.sdk.dartSdkFloor})`:""),i.kept.forEach(({name:a,constraint:l})=>console.log(`Keeping your existing ${a}: ${l||"(non-version source)"}`)),{...o,overridden:n.overridden,warnings:i.warnings,remoteFiles:r.files}}function Ym(t){const e=[],s=[];t.content.length>5e4&&s.push("Code file is large (>50KB). This may take longer to commit."),t.content.length>1e5&&e.push("Code file is too large (>100KB). Consider splitting into smaller components.");const r=t.content.split(` +`).length;r>500&&s.push(`Code has ${r} lines. Consider breaking it into smaller widgets.`),t.content.includes("setState")&&t.codeType===U.ACTION&&s.push("Using setState in a Custom Action may not work as expected. Consider using a Custom Widget."),t.content.includes("dynamic")&&!t.content.includes("?")&&s.push('Code uses "dynamic" types. Consider adding explicit types for better null safety.'),t.content.match(/Color\(0xFF[0-9A-Fa-f]{6}\)/)&&s.push("Code contains hardcoded colors. Consider using FlutterFlowTheme.of(context) for theme consistency.");const i=t.content.match(/print\s*\(/g);i&&i.length>3&&s.push(`Code contains ${i.length} print statements. Consider removing debug prints before committing.`);const n=Lg(t.content);if(n&&e.push(`FlutterFlow cannot format this code - ${n}. Fix or regenerate before committing.`),t.codeType===U.WIDGET){const o=pd(t.content),a=Ng(t.fileName);if(o.length===0)e.push("No public widget class found (must extend StatelessWidget or StatefulWidget).");else if(!o.includes(a)){const l=`${fd(o[0])}`;e.push(`Widget class name "${o[0]}" does not match the file name "${t.fileName}". FlutterFlow derives the widget from the file name, so it will report "No widget ${a} found". Rename the file to "${l}" or the class to match before committing.`)}}return{canProceed:e.length===0,issues:e,warnings:s}}function Hd(t,e={}){const{artifactType:s="CustomWidget",artifactName:r="GeneratedCode",fileName:i}=e,n=Rg(t);let o=i||r;if(s==="CustomFunction")o="custom_functions.dart";else if(s==="CustomWidget"){const u=pd(n)[0],c=u?fd(u):null;c&&o!==c?(console.warn(`Commit file name "${o}" does not match declared widget class "${u}"; renaming to "${c}" so FlutterFlow can find the widget.`),o=c):o.endsWith(".dart")||(o+=".dart")}else o.endsWith(".dart")||(o+=".dart");let a=U.CODE_FILE;switch(s){case"CustomAction":a=U.ACTION;break;case"CustomWidget":a=U.WIDGET;break;case"CustomFunction":a=U.FUNCTION;break;case"CustomClass":case"CodeFile":a=U.CODE_FILE;break}let l="";return a===U.WIDGET?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; // Begin custom widget code // DO NOT REMOVE OR MODIFY THE CODE ABOVE! -`:o===U.ACTION?a=`// Automatic FlutterFlow imports +`:a===U.ACTION?l=`// Automatic FlutterFlow imports import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import 'package:flutter/material.dart'; // Begin custom action code // DO NOT REMOVE OR MODIFY THE CODE ABOVE! -`:o===U.FUNCTION&&(a=`// Automatic FlutterFlow imports +`:a===U.FUNCTION&&(l=`// Automatic FlutterFlow imports import 'dart:convert'; import 'dart:math' as math; @@ -98,15 +108,15 @@ import '/flutter_flow/lat_lng.dart'; import '/flutter_flow/place.dart'; import '/flutter_flow/uploaded_file.dart'; -`),{content:sg(i,a),fileName:n,codeType:o,artifactType:s,artifactName:r}}function Dm(t){const e={};for(const s of ld(t))e[s]="";return e}function jm(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Um(t,e,s,r=new Set,i=""){const n=[],o=$d.test(e),a=Md.test(e);return s===U.WIDGET&&!o&&!a&&n.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:n.length===0,errors:n}}function Li(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(i=>Pi(i.content||"")));for(const[i,n]of t.entries()){if((!n.content||n.content.trim().length===0)&&e.push(`File ${i} is empty`),n.content&&n.content.length>1e5&&s.push(`File ${i} is very large (>100KB)`),i.endsWith(".dart")){const o=Um(i,n.content,n.type,r,n.artifactName);o.valid||e.push(...o.errors.map(a=>`${i}: ${a}`))}if(i==="pubspec.yaml"){const o=vd(n.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const G={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:G.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=G.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(G).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===G.PREPARING&&(this.startTime=Date.now()),(t===G.SUCCESS||t===G.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(G.ERROR)},setSuccess(t){this.result=t,this.setState(G.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===G.PREPARING||this.currentState===G.VALIDATING||this.currentState===G.PUSHING}};async function Hm(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:i={},artifactName:n=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(G.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!$i(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=ur(),u=new dr(o,a,"main",l);K.setState(G.VALIDATING);const c=new Map,d=r||Lm(e,t),h=Nd(e,d);c.set(e,{artifactName:n,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Li(c);if(!p.valid)throw new Error(`Validation failed: +`),{content:og(n,l),fileName:o,codeType:a,artifactType:s,artifactName:r}}function Zm(t){const e={};for(const s of dd(t))e[s]="";return e}function Xm(t,e={}){return{timestamp:new Date().toISOString(),artifactType:t.artifactType,artifactName:t.artifactName,codeType:t.codeType,fileName:t.fileName,generatedFrom:e.step1Result?"pipeline":"direct",model:e.selectedModel||"unknown",codeSize:t.content.length}}function Qm(t,e,s,r=new Set,i=""){const n=[],o=Bd.test(e),a=Dd.test(e);return s===U.WIDGET&&!o&&!a&&n.push("No widget class definition found (must extend StatelessWidget or StatefulWidget)"),{valid:n.length===0,errors:n}}function Bi(t){const e=[],s=[];if(!t||t.size===0)return e.push("No files to commit"),{valid:!1,errors:e,warnings:s};const r=new Set(Array.from(t.values()).flatMap(i=>Ai(i.content||"")));for(const[i,n]of t.entries()){if((!n.content||n.content.trim().length===0)&&e.push(`File ${i} is empty`),n.content&&n.content.length>1e5&&s.push(`File ${i} is very large (>100KB)`),i.endsWith(".dart")){const o=Qm(i,n.content,n.type,r,n.artifactName);o.valid||e.push(...o.errors.map(a=>`${i}: ${a}`))}if(i==="pubspec.yaml"){const o=Ed(n.content);o.valid||e.push(...o.errors)}}return{valid:e.length===0,errors:e,warnings:s}}const G={IDLE:"IDLE",PREPARING:"PREPARING",VALIDATING:"VALIDATING",PUSHING:"PUSHING",SUCCESS:"SUCCESS",ERROR:"ERROR"},K={currentState:G.IDLE,startTime:null,endTime:null,error:null,result:null,filesProcessed:0,totalFiles:0,reset(){this.currentState=G.IDLE,this.startTime=null,this.endTime=null,this.error=null,this.result=null,this.filesProcessed=0,this.totalFiles=0},setState(t){if(!Object.values(G).includes(t)){console.error(`Invalid commit state: ${t}`);return}this.currentState=t,t===G.PREPARING&&(this.startTime=Date.now()),(t===G.SUCCESS||t===G.ERROR)&&(this.endTime=Date.now()),typeof window<"u"&&window.dispatchEvent&&window.dispatchEvent(new CustomEvent("commitStateChange",{detail:{state:t,commitState:this}})),console.log(`Commit state changed to: ${t}`)},setError(t){this.error=t,this.setState(G.ERROR)},setSuccess(t){this.result=t,this.setState(G.SUCCESS)},setProgress(t,e){this.filesProcessed=t,this.totalFiles=e},getElapsedTime(){return this.startTime?(this.endTime||Date.now())-this.startTime:null},isInProgress(){return this.currentState===G.PREPARING||this.currentState===G.VALIDATING||this.currentState===G.PUSHING}};async function ev(t,e,s={}){let{codeType:r="W"}=s;const{pubspecDeps:i={},artifactName:n=e}=s;r==="CustomWidget"&&(r=U.WIDGET),r==="CustomAction"&&(r=U.ACTION),r==="CustomFunction"&&(r=U.FUNCTION),r==="CustomClass"&&(r=U.CODE_FILE),r==="CodeFile"&&(r=U.CODE_FILE),K.reset(),K.setState(G.PREPARING);try{const o=await Ee("flutterflow"),a=await Ee("flutterflow_project_id");if(!o||!a)throw new Error("FlutterFlow credentials not configured. Please set your API key and Project ID in the API Keys settings.");if(!Ni(a))throw new Error("Invalid FlutterFlow Project ID format.");const l=ur(),u=new dr(o,a,"main",l);K.setState(G.VALIDATING);const c=new Map,d=r||Jm(e,t),h=jd(e,d);c.set(e,{artifactName:n,content:t,type:d,path:h}),K.setProgress(0,c.size);const p=Bi(c);if(!p.valid)throw new Error(`Validation failed: ${p.errors.join(` -`)}`);const f=await ha(u,i),g=f.yaml,v=await da(u,c,f.remoteFiles,`Provision ${n} custom class`),_=await ua(v.syncFileMap,v.remoteFiles),w=new Map(v.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const S=await pa(w),k={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(G.PUSHING),K.setProgress(1,c.size),Oi(u),be.set("push");const E=await u.pushCode(k),P=await la(E);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const B=P.errorMessage||ca(P.responseCode);throw new Error(B)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function pa(t){try{const e=new JSZip;for(const[r,i]of t.entries())e.file(r,i.content);return await e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}catch(e){return console.error("Error creating zip:",e),""}}async function Wm(t,e={}){const{artifactType:s,artifactName:r,pipelineResult:i}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(G.PREPARING);const n=Ld(t,{artifactType:s,artifactName:r}),o=Dm(n.content);console.log("Detected dependencies:",o),K.setState(G.VALIDATING);const a=await Ee("flutterflow"),l=Js||await Ee("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(!$i(l))throw new Error("Invalid FlutterFlow Project ID format.");const u=new Map;u.set(n.fileName,{artifactName:r,content:n.content,type:n.codeType,path:Nd(n.fileName,n.codeType),functionName:n.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,u.size);const c=Li(u);if(!c.valid)throw new Error(`File validation failed: -${c.errors.join(` -`)}`);c.warnings.length>0&&console.warn("Validation warnings:",c.warnings),K.setState(G.PUSHING);const d=ur(),h=new dr(a,l,"main",d),p=await ha(h,o),f=p.yaml,g=await da(h,u,p.remoteFiles,`Provision ${r} custom class`),v=await ua(g.syncFileMap,g.remoteFiles),_=new Map(g.syncFileMap);_.set("pubspec.yaml",{content:f,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const w=await pa(_),S={project_id:l,zipped_custom_code:w,uid:`web_${Date.now()}`,branch_name:h.branchName,serialized_yaml:f,file_map:v.fileMapContents,functions_map:v.functionsMapContents};K.setProgress(1,u.size),Oi(h),be.set("push");const k=await h.pushCode(S),E=await la(k);if(E.success){const P={...jm(n,i),projectId:l};return K.setSuccess({...P,fileCount:u.size,warnings:E.errorMap?Array.from(E.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${n.fileName} to FlutterFlow`,metadata:P,addedDependencies:p.added,warnings:E.errorMap?Array.from(E.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const P=E.errorMessage||ca(E.responseCode),B=new Error(P);throw B.errorMap=E.errorMap,B}}catch(n){console.error("Commit execution failed:",n),K.setError(n);let o=new Map;if(n.errorMap)o=n.errorMap;else if(n.message&&n.message.includes("{"))try{const a=n.message.match(/\{[\s\S]*\}/);if(a){const l=JSON.parse(a[0]);o=new Map(Object.entries(l))}}catch(a){console.warn("Failed to parse error map from commit response:",a)}return{success:!1,error:n.message,errorMap:o,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function zm(t,e={}){var r;const{pipelineResult:s}=e;try{if(K.setState(G.PREPARING),((r=t.errors)==null?void 0:r.length)>0)throw new Error(`Bundle validation failed: +`)}`);const f=await fa(u,i),g=f.yaml,v=await pa(u,c,f.remoteFiles,`Provision ${n} custom class`),_=await ha(v.syncFileMap,v.remoteFiles),w=new Map(v.syncFileMap);w.set("pubspec.yaml",{content:g,type:"D",path:"pubspec.yaml"}),be.set("package");const S=await ga(w),k={project_id:a,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setState(G.PUSHING),K.setProgress(1,c.size),Li(u),be.set("push");const x=await u.pushCode(k),P=await ua(x);if(P.success)K.setSuccess({fileCount:c.size,projectId:a,warnings:P.errorMap&&P.errorMap.size>0?Array.from(P.errorMap.entries()):[]});else{const M=P.errorMessage||da(P.responseCode);throw new Error(M)}return{success:!0,message:`Successfully committed ${e} to FlutterFlow project ${a}`,addedDependencies:f.added,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}}catch(o){return console.error("Commit failed:",o),K.setError(o),{success:!1,error:o.message,state:K.currentState}}}async function ga(t){const e=new JSZip;for(const[s,r]of t.entries())e.file(s,r.content);return e.generateAsync({type:"base64",compression:"DEFLATE",compressionOptions:{level:6}})}async function tv(t,e={}){const{artifactType:s,artifactName:r,fileName:i,pipelineResult:n}=e;console.log(`Starting commit for ${r} (${s})`);try{K.setState(G.PREPARING);const o=Hd(t,{artifactType:s,artifactName:r,fileName:i}),a=Zm(o.content);console.log("Detected dependencies:",a),K.setState(G.VALIDATING);const l=await Ee("flutterflow"),u=Js||await Ee("flutterflow_project_id");if(!l)throw new Error("FlutterFlow API Key not configured. Please add it in API Keys settings.");if(!u)throw new Error("FlutterFlow Project ID not configured. Please add it in API Keys settings.");if(!Ni(u))throw new Error("Invalid FlutterFlow Project ID format.");const c=new Map;c.set(o.fileName,{artifactName:r,content:o.content,type:o.codeType,path:jd(o.fileName,o.codeType),functionName:o.codeType===U.FUNCTION?r:void 0}),K.setProgress(0,c.size);const d=Bi(c);if(!d.valid)throw new Error(`File validation failed: +${d.errors.join(` +`)}`);d.warnings.length>0&&console.warn("Validation warnings:",d.warnings),K.setState(G.PUSHING);const h=ur(),p=new dr(l,u,"main",h),f=await fa(p,a),g=f.yaml,v=await pa(p,c,f.remoteFiles,`Provision ${r} custom class`),_=await ha(v.syncFileMap,v.remoteFiles),w=new Map(v.syncFileMap);w.set("pubspec.yaml",{content:g,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const S=await ga(w),k={project_id:u,zipped_custom_code:S,uid:`web_${Date.now()}`,branch_name:p.branchName,serialized_yaml:g,file_map:_.fileMapContents,functions_map:_.functionsMapContents};K.setProgress(1,c.size),Li(p),be.set("push");const x=await p.pushCode(k),P=await ua(x);if(P.success){const M={...Xm(o,n),projectId:u};return K.setSuccess({...M,fileCount:c.size,warnings:P.errorMap?Array.from(P.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${o.fileName} to FlutterFlow`,metadata:M,addedDependencies:f.added,warnings:P.errorMap?Array.from(P.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}else{const M=P.errorMessage||da(P.responseCode),E=new Error(M);throw E.errorMap=P.errorMap,E}}catch(o){console.error("Commit execution failed:",o),K.setError(o);let a=new Map;if(o.errorMap)a=o.errorMap;else if(o.message&&o.message.includes("{"))try{const l=o.message.match(/\{[\s\S]*\}/);if(l){const u=JSON.parse(l[0]);a=new Map(Object.entries(u))}}catch(l){console.warn("Failed to parse error map from commit response:",l)}return{success:!1,error:o.message,errorMap:a,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function sv(t,e={}){var r;const{pipelineResult:s}=e;try{if(K.setState(G.PREPARING),((r=t.errors)==null?void 0:r.length)>0)throw new Error(`Bundle validation failed: ${t.errors.join(` -`)}`);const i=new Map(t.fileEntries.map(E=>[E.fileName,{artifactId:E.artifactId,artifactName:E.artifactName,content:E.content,type:E.type,path:E.path,functionName:E.type===U.FUNCTION?E.artifactName:void 0}]));K.setProgress(0,i.size);const n=Li(i);if(!n.valid)throw new Error(`File validation failed: +`)}`);const i=new Map(t.fileEntries.map(x=>[x.fileName,{artifactId:x.artifactId,artifactName:x.artifactName,content:x.content,type:x.type,path:x.path,functionName:x.type===U.FUNCTION?x.artifactName:void 0}]));K.setProgress(0,i.size);const n=Bi(i);if(!n.valid)throw new Error(`File validation failed: ${n.errors.join(` -`)}`);K.setState(G.VALIDATING);const o=await Ee("flutterflow"),a=Js||await Ee("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(!$i(a))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(G.PUSHING);const l=ur(),u=new dr(o,a,"main",l),c=await ha(u,t.dependencies),d=c.yaml,h=await da(u,i,c.remoteFiles,`Provision ${t.title} custom classes`),p=await ua(h.syncFileMap,h.remoteFiles),f=new Map(h.syncFileMap);f.set("pubspec.yaml",{content:d,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const g=await pa(f),v={project_id:a,zipped_custom_code:g,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:d,file_map:p.fileMapContents,functions_map:p.functionsMapContents};K.setProgress(1,i.size),Oi(u),be.set("push");const _=await u.pushCode(v),w=await la(_);if(w.success){const E={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((P,B)=>P+B.content.length,0),projectId:a};return K.setSuccess({...E,fileCount:i.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:E,addedDependencies:c.added,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const S=w.errorMessage||ca(w.responseCode),k=new Error(S);throw k.errorMap=w.errorMap,k}catch(i){return console.error("Bundle commit execution failed:",i),K.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function qm(t,e=[]){const s=Vo("architect");try{return await Ei("architect",Ed,Ef(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function Bi(t,e,s=[]){const r=Sf(t),i=Vo("generator",y.bundleSpec);try{return await Ei("generator",e,r,i,s)}catch(n){if(n.isModelArmor)throw n;if(e!==xn){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,n.message);try{return await Ei("generator",xn,r,i,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${n.message} | fallback (${xn}): ${o.message}`)}}throw new Error(`Code Generator failed: ${n.message}`)}}async function Di(t,e=null){const s={...Vo("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Ei("review",Sd,xf(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function fa(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function bo(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` +`)}`);K.setState(G.VALIDATING);const o=await Ee("flutterflow"),a=Js||await Ee("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(!Ni(a))throw new Error("Invalid FlutterFlow Project ID format.");K.setState(G.PUSHING);const l=ur(),u=new dr(o,a,"main",l),c=await fa(u,t.dependencies),d=c.yaml,h=await pa(u,i,c.remoteFiles,`Provision ${t.title} custom classes`),p=await ha(h.syncFileMap,h.remoteFiles),f=new Map(h.syncFileMap);f.set("pubspec.yaml",{content:d,type:U.DEPENDENCIES,path:"pubspec.yaml"}),be.set("package");const g=await ga(f),v={project_id:a,zipped_custom_code:g,uid:`web_${Date.now()}`,branch_name:u.branchName,serialized_yaml:d,file_map:p.fileMapContents,functions_map:p.functionsMapContents};K.setProgress(1,i.size),Li(u),be.set("push");const _=await u.pushCode(v),w=await ua(_);if(w.success){const x={...s,artifactType:"Bundle",artifactName:t.title,fileName:`${t.fileEntries.length} artifacts`,codeSize:t.fileEntries.reduce((P,M)=>P+M.content.length,0),projectId:a};return K.setSuccess({...x,fileCount:i.size,warnings:w.errorMap?Array.from(w.errorMap.entries()):[]}),{success:!0,message:`Successfully committed ${t.fileEntries.length} artifacts to FlutterFlow`,metadata:x,addedDependencies:c.added,warnings:w.errorMap?Array.from(w.errorMap.entries()):[],elapsedTime:K.getElapsedTime()}}const S=w.errorMessage||da(w.responseCode),k=new Error(S);throw k.errorMap=w.errorMap,k}catch(i){return console.error("Bundle commit execution failed:",i),K.setError(i),{success:!1,error:i.message,errorMap:i.errorMap||new Map,state:K.currentState,elapsedTime:K.getElapsedTime()}}}async function rv(t,e=[]){const s=Go("architect");try{return await Si("architect",Cd,Cf(t),s,e)}catch(r){throw r.isModelArmor?r:new Error(`Prompt Architect failed: ${r.message}`)}}async function Di(t,e,s=[]){const r=Ff(t),i=Go("generator",y.bundleSpec);try{return await Si("generator",e,r,i,s)}catch(n){if(n.isModelArmor)throw n;if(e!==kn){console.warn(`Code Generator failed with ${e}, retrying with fallback model:`,n.message);try{return await Si("generator",kn,r,i,s)}catch(o){throw o.isModelArmor?o:new Error(`Code Generator failed: primary (${e}): ${n.message} | fallback (${kn}): ${o.message}`)}}throw new Error(`Code Generator failed: ${n.message}`)}}async function ji(t,e=null){const s={...Go("review",y.artifactBundle||y.bundleSpec),architect_output:e};try{return await Si("review",Fd,Pf(t),s)}catch(r){throw r.isModelArmor?r:new Error(`Code Review failed: ${r.message}`)}}function ma(t,e){return t.isModelArmor?`${t.userTitle}: ${t.userMessage}`:`${e}: ${t.message}`}function Eo(t,e){const s=document.getElementById(`step${t}-item`),r=document.getElementById(`step${t}-status`);!s||!r||(s.classList.remove("active","completed","error"),r.classList.remove("running","completed","error"),e==="active"?(s.classList.add("active"),r.classList.add("running"),r.innerHTML=` `):e==="completed"?(s.classList.add("completed"),r.classList.add("completed"),r.innerHTML=` @@ -114,15 +124,15 @@ ${n.errors.join(` `):r.innerHTML=` - `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),bo(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),bo(t,"completed"))}function Vm(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function Gm(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Jt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const i=document.getElementById("stage-title"),n={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};i&&(i.textContent=n[t]||"Active Workflow Stage")}function Km(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{Ht("Code Copied",{elementId:t});const r=e.closest(".code-container"),i=r==null?void 0:r.querySelector(".copy-btn");i&&(i.classList.add("copied"),i.innerHTML=' Copied!',setTimeout(()=>{i.classList.remove("copied"),i.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function Eo(t){const e=xo(t);console.log(`Step 1 (Prompt Architect): ${Wt(Ed)}`),console.log(e!==t?`Step 2 (Code Generator): ${Wt(t)} → ${Wt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Wt(t)}`),console.log(`Step 3 (Code Review): ${Wt(Sd)}`)}async function Jm(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,ga("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` + `)}function ve(t,e){const s=document.getElementById(`step${t}-loading`),r=document.getElementById(`step${t}-result`);e?(s.classList.remove("hidden"),r.classList.add("hidden"),Eo(t,"active")):(s.classList.add("hidden"),r.classList.remove("hidden"),Eo(t,"completed"))}function iv(t){const e=document.getElementById(`${t}-content`),s=document.getElementById(`${t}-chevron`);e.classList.contains("open")?(e.classList.remove("open"),s&&(s.style.transform="rotate(0deg)")):(e.classList.add("open"),s&&(s.style.transform="rotate(180deg)"))}function nv(t){ze(parseInt(t.replace("step","")))}function ze(t){for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-item`);a&&a.classList.remove("active")}const e=document.getElementById(`step${t}-item`);e&&e.classList.add("active"),Jt();const s=document.getElementById("ready-state");s&&s.classList.add("hidden");for(let o=1;o<=3;o++){const a=document.getElementById(`step${o}-content`);a&&a.classList.add("hidden")}const r=document.getElementById(`step${t}-content`);r&&r.classList.remove("hidden");const i=document.getElementById("stage-title"),n={1:"Prompt Architect",2:"Code Generator",3:"Code Review"};i&&(i.textContent=n[t]||"Active Workflow Stage")}function ov(t){const e=document.getElementById(t);if(!e)return;const s=e.dataset.raw||e.textContent;navigator.clipboard.writeText(s).then(()=>{Ht("Code Copied",{elementId:t});const r=e.closest(".code-container"),i=r==null?void 0:r.querySelector(".copy-btn");i&&(i.classList.add("copied"),i.innerHTML=' Copied!',setTimeout(()=>{i.classList.remove("copied"),i.innerHTML=' Copy'},2e3))}).catch(r=>{console.warn("Failed to copy to clipboard:",r)})}function So(t){const e=ko(t);console.log(`Step 1 (Prompt Architect): ${Wt(Cd)}`),console.log(e!==t?`Step 2 (Code Generator): ${Wt(t)} → ${Wt(e)} (Free Tier fallback)`:`Step 2 (Code Generator): ${Wt(t)}`),console.log(`Step 3 (Code Review): ${Wt(Fd)}`)}async function av(){if(console.log("runRefinement called"),y.isRunning)return;const t=document.getElementById("code-generator-model").value;y.isRunning=!0,va("standardRegenerate",y.step2Result,y.step1Result);const e=document.querySelectorAll(".btn-refine-action");e.forEach(s=>{s.disabled=!0,s.innerHTML=` - Refining...`});try{const s=oa(),r=kf({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});Wi(),rt(2),ze(2),ve(2,!0),y.step2Result=await Bi(r,t),Mi();const i=document.getElementById("step2-output"),n=ws(y.step2Result);i.textContent=n,i.dataset.raw=n,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Di(y.step2Result,y.step1Result),Ni();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Pt();const a=Ri(y.step3Result);zi(n,a)}catch(s){console.error("Refinement failed:",s),Pt(),ue(fa(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Yt()}}async function ga(t,e,s){const r=`${Ke}/connectFeedback`,i={type:t,code:e,input:s};try{const n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const a=await n.text();return console.error(`callEndpoint failed: ${n.status} ${n.statusText}`,a),{success:!1,status:n.status,error:a}}const o=await n.json();return console.log("Telemetry success:",o),o}catch(n){return console.error("callEndpoint failed:",n),{success:!1,error:n.message}}}function Ym(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function Zm(){var i;const t=document.getElementById("ff-error-paste-input"),e=(i=t==null?void 0:t.value)==null?void 0:i.trim();if(!e){t==null||t.focus(),t==null||t.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t==null?void 0:t.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,ga("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` + Refining...`});try{const s=la(),r=Af({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,artifactId:s.id,userFeedback:"Fix the issues listed in the audit report."});zi(),rt(2),ze(2),ve(2,!0),y.step2Result=await Di(r,t),Mi();const i=document.getElementById("step2-output"),n=ws(y.step2Result);i.textContent=n,i.dataset.raw=n,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await ji(y.step2Result,y.step1Result),Oi();const o=document.getElementById("step3-output");o.textContent=y.step3Result,ve(3,!1),Pt();const a=Ri(y.step3Result);qi(n,a)}catch(s){console.error("Refinement failed:",s),Pt(),ue(ma(s,"Refinement failed"),"error")}finally{y.isRunning=!1,e.forEach(s=>{s.disabled=!1,s.textContent="Refine & Regenerate"}),Yt()}}async function va(t,e,s){const r=`${Ke}/connectFeedback`,i={type:t,code:e,input:s};try{const n=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!n.ok){const a=await n.text();return console.error(`callEndpoint failed: ${n.status} ${n.statusText}`,a),{success:!1,status:n.status,error:a}}const o=await n.json();return console.log("Telemetry success:",o),o}catch(n){return console.error("callEndpoint failed:",n),{success:!1,error:n.message}}}function lv(){const t=document.getElementById("ff-error-paste-input");t&&(t.value="")}async function cv(){var i;const t=document.getElementById("ff-error-paste-input"),e=(i=t==null?void 0:t.value)==null?void 0:i.trim();if(!e){t==null||t.focus(),t==null||t.classList.add("ring-2","ring-red-400","border-red-300"),setTimeout(()=>t==null?void 0:t.classList.remove("ring-2","ring-red-400","border-red-300"),2e3);return}if(!y.step2Result){ue("No generated code found. Please run the full pipeline first.","warning");return}if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0,va("flutterflowError",y.step2Result,e);const r=document.getElementById("btn-fix-from-errors");r&&(r.disabled=!0,r.innerHTML=` - Fixing…`);try{const n=id({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Kd(),Wi(),rt(2),ze(2),ve(2,!0),y.step2Result=await Bi(n,s),Mi();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Di(y.step2Result,y.step1Result),Ni();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Pt();const u=Ri(y.step3Result);zi(a,u),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),Pt(),ue(fa(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Yt()}}async function So(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await vv())return;const s=xo(e);Ht("Pipeline Started",{selectedModel:e,effectiveModel:s,inputLength:t.length});const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,Mm(),r.disabled=!0,r.innerHTML=` + Fixing…`);try{const n=ad({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:e});Qd(),zi(),rt(2),ze(2),ve(2,!0),y.step2Result=await Di(n,s),Mi();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await ji(y.step2Result,y.step1Result),Oi();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Pt();const u=Ri(y.step3Result);qi(a,u),t&&(t.value="")}catch(n){console.error("Fix from errors failed:",n),Pt(),ue(ma(n,"Failed to fix errors"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Yt()}}async function xo(){if(console.log("runThinkingPipeline called"),y.isRunning)return;localStorage.setItem("hasSeenWalkthrough","true");const t=document.getElementById("pipeline-input").value,e=document.getElementById("code-generator-model").value;if(!t.trim()){ue("Please describe your FlutterFlow widget first.","warning");return}if(!await Pv())return;const s=ko(e);Ht("Pipeline Started",{selectedModel:e,effectiveModel:s,inputLength:t.length});const r=document.getElementById("btn-run-pipeline");y.isRunning=!0,Vm(),r.disabled=!0,r.innerHTML=` - Running...`,Eo(s);try{Jt();const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const n=document.getElementById("paywall-exhausted");n&&n.classList.add("hidden"),Wi(),ze(1),rt(1),ve(1,!0);const o=Ft.filter(p=>p.url).map(p=>({url:p.url}));y.step1Result=await qm(t,o),Nm(),Ht("Prompt Architect Completed");const a=document.getElementById("step1-output"),l=ws(y.step1Result);a.textContent=l,a.dataset.raw=l,ve(1,!1),ze(2),rt(2),ve(2,!0),y.step2Result=await Bi(y.step1Result,s,o),Mi(),Ht("Code Generator Completed");const u=document.getElementById("step2-output"),c=ws(y.step2Result);u.textContent=c,u.dataset.raw=c,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Di(y.step2Result,y.step1Result),Ni(),Ht("Code Review Completed");const d=document.getElementById("step3-output");d.textContent=y.step3Result,ve(3,!1),Pt();const h=Ri(y.step3Result);zi(c,h),hv(),Ui()}catch(i){if(console.error("Pipeline failed:",i),Pt(),i.isUsageLimit){const{count:c}=ji();Ea(c,ba(),{openModal:!0});return}Ht("Pipeline Failed",{error:i.message,effectiveModel:xo(document.getElementById("code-generator-model").value)});const o=Vg(i,{architect:1,generator:2,review:3});ze(o);const a=document.getElementById(`step${o}-result`),l=document.getElementById(`step${o}-loading`),u=document.getElementById(`step${o}-output`);if(l&&l.classList.add("hidden"),a&&a.classList.remove("hidden"),u)if(i.isModelArmor)u.innerHTML=``}bo(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` + `}Eo(o,"error")}finally{y.isRunning=!1,r.disabled=!1,r.innerHTML=` - Run Pipeline`,Yt()}}function Xm(){const t=document.getElementById("code-generator-model").value,e=[nr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? + Run Pipeline`,Yt()}}function uv(){const t=document.getElementById("code-generator-model").value,e=[nr,"anthropic/claude-opus-5","openai/gpt-5.6-sol"].filter(r=>r!==t),s=prompt(`Retry with different model? Current: ${t} @@ -145,14 +155,14 @@ Options: 1. ${e[0]} 2. ${e[1]} -Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],So()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],So())}async function Qm(){var a,l;const t=aa();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ra();return}if(((l=(a=y.artifactBundle)==null?void 0:a.artifacts)==null?void 0:l.length)>1){await ev();return}const{artifactType:r,artifactName:i}=Td(),n=Ld(t,{artifactType:r,artifactName:i}),o=Bm(n);if(!o.canProceed){ue(`Pre-commit checks failed: ${o.issues.join("; ")}`,"error");return}Ud(n,o,null,null)}async function ev(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),ra();return}const s=cg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),i=Li(r),n={canProceed:i.valid&&s.errors.length===0,issues:[...s.errors,...i.errors],warnings:[...s.warnings,...i.warnings]};if(!n.canProceed){ue(`Bundle validation failed: ${n.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} +Enter 1 or 2:`);s==="1"?(document.getElementById("code-generator-model").value=e[0],xo()):s==="2"&&(document.getElementById("code-generator-model").value=e[1],xo())}async function dv(){var l,u;const t=ca();if(!t){ue("No code to commit. Please run the pipeline first.","warning");return}const e=await Ee("flutterflow"),s=await Ee("flutterflow_project_id");if(!e||!s){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),na();return}if(((u=(l=y.artifactBundle)==null?void 0:l.artifacts)==null?void 0:u.length)>1){await hv();return}const{artifactType:r,artifactName:i,fileName:n}=Ld(),o=Hd(t,{artifactType:r,artifactName:i,fileName:n}),a=Ym(o);if(!a.canProceed){ue(`Pre-commit checks failed: ${a.issues.join("; ")}`,"error");return}Vd(o,a,null,null)}async function hv(){const t=await Ee("flutterflow"),e=await Ee("flutterflow_project_id");if(!t||!e){ue("FlutterFlow credentials not configured. Add your API Key and Project ID in settings.","warning"),na();return}const s=pg(y.artifactBundle);if(s.errors.length>0){ue(`Bundle validation failed: ${s.errors.join("; ")}`,"error");return}const r=new Map(s.fileEntries.map(a=>[a.fileName,{content:a.content,type:a.type,path:a.path}])),i=Bi(r),n={canProceed:i.valid&&s.errors.length===0,issues:[...s.errors,...i.errors],warnings:[...s.warnings,...i.warnings]};if(!n.canProceed){ue(`Bundle validation failed: ${n.issues.join("; ")}`,"error");return}const o={content:s.fileEntries.map(a=>`// ${a.fileName} ${a.content}`).join(` -`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};Ud(o,n,s.dependencies,s)}function tv(t){var i;let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`
+`),fileName:`${s.fileEntries.length} files`,codeType:"bundle",artifactType:"Bundle",artifactName:s.title};Vd(o,n,s.dependencies,s)}function pv(t){var i;let e=t.errorMap||new Map;!(e instanceof Map)&&typeof e=="object"&&(e=new Map(Object.entries(e)));let s=`

FlutterFlow Commit Failed

${j(t.error)}

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

Errors:

-
    `;for(const[n,o]of e.entries()){const a=ud(o);s+=`
  • +
      `;for(const[n,o]of e.entries()){const a=gd(o);s+=`
    • ${j(n)}: ${j(a)}
    • `}s+="
"}s+="
",s+=`
-
`;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,(i=document.getElementById("btn-regenerate-from-error"))==null||i.addEventListener("click",()=>{sv(t.error,e)}))}async function sv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` +
`;const r=document.getElementById("step3-output");r&&(r.innerHTML=s,(i=document.getElementById("btn-regenerate-from-error"))==null||i.addEventListener("click",()=>{fv(t.error,e)}))}async function fv(t,e){if(y.isRunning)return;const s=document.getElementById("code-generator-model").value;y.isRunning=!0;const r=document.getElementById("btn-regenerate-from-error");r&&(r.disabled=!0,r.innerHTML=` Fixing...`);try{let i=`The previous code had the following errors when committing to FlutterFlow: -`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=ud(d);i+=`File: ${c} +`;if(e&&e.size>0)for(const[c,d]of e.entries()){const h=gd(d);i+=`File: ${c} Error: ${h} `}else i+=`${t} -`;const n=id({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:i});Wi(),rt(2),ze(2),ve(2,!0),y.step2Result=await Bi(n,s),Mi();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await Di(y.step2Result,y.step1Result),Ni();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Pt();const u=Ri(y.step3Result);zi(a,u)}catch(i){console.error("Regeneration failed:",i),Pt(),ue(fa(i,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Yt()}}async function rv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function iv(t){try{const e=await fetch(`${Ke}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function nv(t){try{const s=await(await fetch(`${Ke}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function ov(t){try{const e=await fetch(`${Ke}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ke}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ke}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function uc(t,e){const s=Bd(),r=(q.email||s.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(fi,JSON.stringify({email:t,sessionToken:e})),r&&Sa()}function ma(){q.email=null,q.sessionToken=null,q.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(fi),localStorage.removeItem(mi)}function Bd(){try{const t=localStorage.getItem(fi);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(fi),{email:null,sessionToken:null}}}async function av(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await nv(e);uc(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Bd();if(s&&r){const i=await ov(r);i?uc(i.email,i.sessionToken):ma()}}_a()}function va(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function lv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function cv(){var n;const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=(n=t==null?void 0:t.value)==null?void 0:n.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await iv(r),t&&(t.value=""),s&&(s.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}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function uv(){ma(),Sa(),_a(),Hi()}function _a(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const i=document.getElementById("auth-user-email");i&&(i.textContent=q.email||""),Ur(),Hi()}async function dv(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(tm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const i=await r.json();if(Or.userId=i.user_id,Or.status=i.status,Or.resolved=!0,sessionStorage.setItem(em,i.user_id),i.usage_count!==void 0){const n=Gt(),o=i.usage_month||n,a=o===n?i.usage_count:0,l=ya(),u=l.month===n?l.count:0;(a>=u||o>l.month)&&localStorage.setItem(ds,JSON.stringify({count:a,month:n})),Ui()}console.log(`Identity resolved: ${i.status} (${i.user_id.slice(0,8)}...) usage: ${i.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}function ya(){const t=Gt();try{const e=localStorage.getItem(ds);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:ds,month:t,err:e}),localStorage.removeItem(ds),{count:0,month:t}}}function Gt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function ji(){const t=ya();return t.month!==Gt()?{count:0,month:Gt()}:t}function hv(){const e={count:ji().count+1,month:Gt()};return localStorage.setItem(ds,JSON.stringify(e)),e}function wa(){return!!fe.isLoading}function Kt(){return!!fe.isResolved}function pv(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(gi,e)?e:null}function fv(t){var e;return t&&((e=Object.entries(yd).find(([,s])=>s===t))==null?void 0:e[0])||null}function Cr(...t){return t.find(e=>e!=null&&e!=="")}function gv(...t){return t.find(e=>e&&typeof e=="object")||{}}function mv(t){var c,d,h,p,f,g,v,_,w,S,k,E,P,B,x,A,R,M,$,N;const e=t.data&&typeof t.data=="object"?t.data:t,s=gv(e.subscription,e.stripeSubscription,e.currentSubscription,(h=(d=(c=e.customer)==null?void 0:c.subscriptions)==null?void 0:d.data)==null?void 0:h[0],(f=(p=e.subscriptions)==null?void 0:p.data)==null?void 0:f[0],(g=e.subscriptions)==null?void 0:g[0]),r=e.metadata||s.metadata||((v=e.customer)==null?void 0:v.metadata)||{},i=Cr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,(_=s.plan)==null?void 0:_.id,(w=s.price)==null?void 0:w.id,(P=(E=(k=(S=s.items)==null?void 0:S.data)==null?void 0:k[0])==null?void 0:E.price)==null?void 0:P.id,(A=(x=(B=s.items)==null?void 0:B[0])==null?void 0:x.price)==null?void 0:A.id,(N=($=(M=(R=s.lines)==null?void 0:R.data)==null?void 0:M[0])==null?void 0:$.price)==null?void 0:N.id),n=Cr(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=pv(Cr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=sm.has(String(n).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||fv(i)||(a||l?"professional":"free");return bs({tier:u,status:n,periodEnd:Cr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function ba(){return gi[fe.tier]??gi.free}async function vv(){if(q.isVerified&&(!Kt()||wa())&&(await Dd({force:!0}),Hi()),q.isVerified&&!Kt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=ji(),e=ba();if(t>=e)return Ea(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function kn(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function Ea(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const n=document.getElementById("preview-frame-container");n&&(n.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),Si();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),s.openModal&&Si()}function xo(t){return fe.tier==="free"&&Lr.includes(t)?nr:t}function _v(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,i=!(q.isVerified&&!Kt())&&s==="free";Array.from(e.options).forEach(o=>{const a=Wt(o.value),l=Lr.includes(o.value);o.textContent=l&&i?`${a} (PRO)`:a,o.disabled=!1}),i&&Lr.includes(e.value)&&(e.value=nr),e.disabled=!1,ec.has(e)||(e.addEventListener("change",()=>{Kt()&&fe.tier==="free"&&Lr.includes(e.value)&&(e.value=nr,Si()),Eo(e.value),bd()}),ec.add(e));let n=document.getElementById("model-selector-free-notice");i?(n||(n=document.createElement("p"),n.id="model-selector-free-notice",n.className="text-xs text-gray-400 mt-1",t.appendChild(n)),n.innerHTML='Free plan — Gemini only. '):n&&n.remove(),Eo(e.value)}function Ui(){const t=document.getElementById("usage-counter");if(!t)return;if(q.isVerified&&wa()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Ur(),kn();return}if(q.isVerified&&!Kt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Ur(),kn();return}const{count:e}=ji(),s=ba();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Ur(),e>=s&&!y.isRunning?Ea(e,s):kn()}function Ur(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=ya(),s=e.month===Gt()?e.count??0:0,r=gi.free;t.textContent=`${s} / ${r} generations used`}async function Dd(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(mi);if(!e&&s)try{const{data:r,email:i,ts:n,version:o}=JSON.parse(s);if(o===tc&&i===q.email&&Date.now()-n<5*60*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const i=await(await fetch(`${Ke}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,email:q.email})})).json();if(i.error){if(["unauthorized","invalid session","expired session"].some(o=>String(i.error).toLowerCase().includes(o))){ma(),_a();return}fe=bs({isResolved:!1,error:i.error});return}fe=mv(i),localStorage.setItem(mi,JSON.stringify({version:tc,data:fe,email:q.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function Sa(){localStorage.removeItem(mi)}async function yv(t){if(!q.isVerified||!q.sessionToken){jd(),va();return}if(!yd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Ke}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:xd()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:i}=r;window.location.href=i}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function wv(){if(!q.isVerified||!q.sessionToken){va();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Ke}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Ei(t,e,s,r={},i=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(Qg,{method:"POST",headers:{"Content-Type":"application/json"},signal:o.signal,body:JSON.stringify({user_id:Or.userId,step:t,model:e,prompt:s,images:i,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(ds,JSON.stringify({count:c.serverCount,month:Gt()})),Ui());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Tf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function bv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),Sa(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Hi(){const t=q.isVerified&&!!q.email,e=fe.tier,s=t&&wa(),r=!t||Kt(),i=document.getElementById("subscription-tier-badge");if(i){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};i.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",i.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const n=document.getElementById("upgrade-prompt");n&&n.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Ev(r?e:null),_v(),bd(),Ui()}function Ev(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([i,{btnId:n,defaultText:o}])=>{const a=document.getElementById(n);a&&(i===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function ko(){const t=xd(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),i=document.getElementById("power-price-note");e&&(e.textContent=rc(sc.professional,t)),s&&(s.textContent=rc(sc.power,t));const n="billed monthly";r&&(r.textContent=n),i&&(i.textContent=n)}function Si(){ko();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),dm().then(()=>ko())}function jd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Sv(),await av(),bv(),await Dd(),Hi(),ko(),await Om(),Rm();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=ur();t.value=s}Ad(),dv();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{bt===2&&e.value.trim().length>0&&(ia(),Ti())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");bt===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");bt===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===G.PREPARING||r===G.VALIDATING||r===G.PUSHING?(be.phaseId||Wd(),hc(r)):(r===G.SUCCESS||r===G.ERROR)&&(hc(r),setTimeout(xi,1e3))})});function Sv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function xv(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jt),document.addEventListener("keydown",Jt))}function Jt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Jt),document.removeEventListener("keydown",Jt),Ad()}let Ys=null;async function kv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++lc,s=()=>e===lc,r=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new dr(r,"").listProjects();if(!s())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),i&&(t.value=i)}catch(n){if(!s())return;console.error("Failed to load projects for deploy:",n),t.innerHTML=''}}}function Iv(){var s;const t=document.getElementById("confirm-project-select");return((s=t==null?void 0:t.value)==null?void 0:s.trim())||null}function Ud(t,e,s,r=null){Ys={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` -`).length,kv();const i=document.getElementById("confirm-deps-list"),n=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(i.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${wt(c)}`:"version resolved from your project";return`
  • • ${wt(u)}: ${d}
  • `}).join(""),n.classList.remove("hidden")):n.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${wt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&l.classList.add("open")}function Hd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Ys=null}function Cv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const n of s){const o=document.getElementById(n);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const i=document.getElementById("success-warnings-list");i&&(i.innerHTML="")}function Io(t){var p,f,g,v;const e=(_,w)=>{const S=document.getElementById(_);S&&(S.textContent=w||"")},s=((p=t.metadata)==null?void 0:p.fileName)||"",r=((f=t.metadata)==null?void 0:f.projectId)||"",i=((g=t.metadata)==null?void 0:g.artifactType)||"",n=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=(v=t.metadata)!=null&&v.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",i),e("success-time",n),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list");t.warnings&&t.warnings.length>0&&c&&d&&(d.innerHTML=t.warnings.map(([_,w])=>`
  • ${j(_)}: ${j(String(w))}
  • `).join(""),c.classList.remove("hidden"));const h=document.getElementById("commit-success-modal");h&&h.classList.add("open")}function Co(t){xi(),tv(t)}function Fv(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const dc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},Pv=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!dc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=dc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Pv.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),n=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&n.push(Av(e)),zd(this.phaseId==="done"?100:s,t.message,n.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function Av(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function Wd(t){be.start(t)}function xi(){be.stop()}function zd(t,e,s,r=null){const i=document.getElementById("commit-progress-bar"),n=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");i&&(i.style.width=`${Math.round(t*10)/10}%`),n&&(n.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function hc(t){const e={[G.PREPARING]:"prepare",[G.VALIDATING]:"validate",[G.PUSHING]:"project",[G.SUCCESS]:"done"};if(t===G.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,zd(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function Rv(t){var e;return t.bundlePlan?t.bundlePlan.fileEntries.some(s=>s.type===U.CODE_FILE):((e=t.codeInfo)==null?void 0:e.codeType)===U.CODE_FILE}async function Tv(){var n,o;if(!Ys){console.error("No pending commit data");return}const t=Ys;if(Js=Iv(),Hd(),Wd({withProvisioning:Rv(t)}),t.bundlePlan){const a=await zm(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:(n=document.getElementById("code-generator-model"))==null?void 0:n.value}});Js=null,xi(),a.success?Io(a):Co(a);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r}=Td(),i=await Wm(e.content,{artifactType:s,artifactName:r,pipelineResult:{step1Result:y.step1Result,selectedModel:(o=document.getElementById("code-generator-model"))==null?void 0:o.value}});Js=null,xi(),i.success?Io(i):Co(i),Ys=null}window.runThinkingPipeline=So;window.toggleStep=Gm;window.toggleSection=Vm;window.selectWorkflowStep=ze;window.copyCode=Km;window.retryWithDifferentModel=Xm;window.openApiKeysModal=ra;window.closeApiKeysModal=Fd;window.closeWalkthroughModal=km;window.openWalkthroughModal=xm;window.advanceWalkthrough=ia;window.commitToFlutterFlow=Hm;function $v(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Mv(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=$v;window.openModelSelector=Mv;window.handlePromptImageSelect=cm;window.removePromptImage=um;window.saveApiKeys=Fm;window.clearAllApiKeys=Pm;window.toggleKeyVisibility=$m;window.handleWelcomeVideoEnd=xv;window.dismissWelcomeVideo=Jt;window.initiateCommitToFlutterFlow=Qm;window.updateFlutterFlowCredentialStatus=rv;window.closeCommitConfirmModal=Hd;window.closeCommitSuccessModal=Cv;window.showCommitSuccessModal=Io;window.showCommitFailureModal=Co;window.toggleCodePreview=Fv;window.confirmCommitToFlutterFlow=Tv;window.runRefinement=Jm;window.regenerateFromPastedErrors=Zm;window.clearErrorInput=Ym;window.setFlutterFlowEndpoint=Sm;window.getFlutterFlowEndpoint=ur;window.commitProgress=be;window.openSignInModal=va;window.closeSignInModal=lv;window.handleMagicLinkRequest=cv;window.handleSignOut=uv;window.startCheckout=yv;window.openCustomerPortal=wv;window.openPricingModal=Si;window.closePricingModal=jd;let hs=null,qd=null;const pc=120;function Wi(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),qd=Date.now();for(let r=1;r<=3;r++){const i=document.getElementById(`pdot-${r}`);i&&(i.className="progress-dot")}rt(1),Nv()}function rt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),i&&(i.textContent=s[t]||s[1]);for(let n=1;n<=3;n++){const o=document.getElementById(`pdot-${n}`);o&&(n{const t=(Date.now()-qd)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/pc*100,i=Math.min(95,r*(1-Math.exp(-t/(pc*.6)))*1.2);s&&(s.style.width=`${i}%`)},250)}function Pt(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function Vd(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Ov(){return kg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Lv(t){return` +`;const n=ad({bundleSpec:y.step1Result,artifactBundle:JSON.stringify(y.artifactBundle||y.step2Result),bundleReview:y.step3Result,userFeedback:i});zi(),rt(2),ze(2),ve(2,!0),y.step2Result=await Di(n,s),Mi();const o=document.getElementById("step2-output"),a=ws(y.step2Result);o.textContent=a,o.dataset.raw=a,ve(2,!1),ze(3),rt(3),ve(3,!0),y.step3Result=await ji(y.step2Result,y.step1Result),Oi();const l=document.getElementById("step3-output");l.textContent=y.step3Result,ve(3,!1),Pt();const u=Ri(y.step3Result);qi(a,u)}catch(i){console.error("Regeneration failed:",i),Pt(),ue(ma(i,"Regeneration failed"),"error")}finally{y.isRunning=!1,r&&(r.disabled=!1,r.textContent="Fix Errors & Regenerate"),Yt()}}async function gv(){const t=document.getElementById("ff-status-dot"),e=document.getElementById("ff-status-text");if(!t||!e)return;const s=await Ee("flutterflow"),r=await Ee("flutterflow_project_id");s&&r?(t.className="w-2 h-2 rounded-full bg-green-500",e.textContent="FlutterFlow credentials configured",e.className="text-green-600"):s||r?(t.className="w-2 h-2 rounded-full bg-yellow-500",e.textContent="FlutterFlow credentials incomplete",e.className="text-yellow-600"):(t.className="w-2 h-2 rounded-full bg-red-500",e.textContent="FlutterFlow credentials not configured",e.className="text-red-600")}async function mv(t){try{const e=await fetch(`${Ke}/auth/send-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({email:t})});if(!e.ok)throw new Error(`Failed to send magic link: HTTP ${e.status}`);return e.json()}catch(e){throw console.error("sendMagicLink failed:",{email:t,message:e.message,stack:e.stack}),e}}async function vv(t){try{const s=await(await fetch(`${Ke}/auth/verify-magic-link`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})})).json();if(s.error||!s.email||!s.sessionToken)throw new Error(s.error||"Invalid or expired link");return s}catch(e){throw console.error("verifyMagicLink failed:",{message:e.message,stack:e.stack}),e}}async function _v(t){try{const e=await fetch(`${Ke}/auth/refresh-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:t})});if(!e.ok)return console.error("refreshSession: non-OK response",{url:`${Ke}/auth/refresh-session`,status:e.status}),null;const s=await e.json();return s.error||!s.email||!s.sessionToken?(console.warn("refreshSession: validation failed",{error:s.error,hasEmail:!!s.email,hasToken:!!s.sessionToken}),null):s}catch(e){return console.error("refreshSession: fetch failed",{url:`${Ke}/auth/refresh-session`,message:e.message,stack:e.stack}),null}}function pc(t,e){const s=Wd(),r=(q.email||s.email)!==t;q.email=t,q.sessionToken=e,q.isVerified=!0,fe=bs({isLoading:!0}),localStorage.setItem(gi,JSON.stringify({email:t,sessionToken:e})),r&&ka()}function _a(){q.email=null,q.sessionToken=null,q.isVerified=!1,fe=bs({isResolved:!0}),localStorage.removeItem(gi),localStorage.removeItem(vi)}function Wd(){try{const t=localStorage.getItem(gi);if(!t)return{email:null,sessionToken:null};const e=JSON.parse(t);return!e.email||!e.sessionToken?{email:null,sessionToken:null}:e}catch(t){return console.warn("getStoredSession: failed to parse auth session:",t),localStorage.removeItem(gi),{email:null,sessionToken:null}}}async function yv(){const e=new URLSearchParams(window.location.search).get("token");if(e){window.history.replaceState({},"",window.location.pathname);try{const{email:s,sessionToken:r}=await vv(e);pc(s,r)}catch(s){ue(s.message||"Sign-in link invalid or expired.","error")}}else{const{email:s,sessionToken:r}=Wd();if(s&&r){const i=await _v(r);i?pc(i.email,i.sessionToken):_a()}}wa()}function ya(){const t=document.getElementById("signin-modal");t&&t.classList.add("open")}function wv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("signin-modal");e&&e.classList.remove("open")}async function bv(){var n;const t=document.getElementById("signin-email-input"),e=document.getElementById("signin-submit-btn"),s=document.getElementById("signin-message"),r=(n=t==null?void 0:t.value)==null?void 0:n.trim();if(!r||!/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(r)||r.length>254){s&&(s.textContent="Please enter a valid email address.");return}e&&(e.disabled=!0,e.textContent="Sending…"),s&&(s.textContent="");try{await mv(r),t&&(t.value=""),s&&(s.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}),s&&(s.textContent="Something went wrong. Please try again."),e&&(e.disabled=!1,e.textContent="Send Link")}}function Ev(){_a(),ka(),wa(),Wi()}function wa(){const t=q.isVerified&&!!q.email,e=document.getElementById("auth-signedout"),s=document.getElementById("auth-signedin"),r=document.getElementById("auth-guest-usage");e&&e.classList.toggle("hidden",t),s&&s.classList.toggle("hidden",!t),r&&r.classList.toggle("hidden",t);const i=document.getElementById("auth-user-email");i&&(i.textContent=q.email||""),Hr(),Wi()}async function Sv(){try{if(typeof FingerprintJS>"u"){console.warn("resolveIdentity: FingerprintJS not loaded, skipping");return}const e=await(await FingerprintJS.load()).get(),s=e.visitorId,r=await fetch(pm,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fingerprint:e.visitorId,cookie_id:s})});if(!r.ok)throw new Error(`Identity check HTTP ${r.status}`);const i=await r.json();if(Lr.userId=i.user_id,Lr.status=i.status,Lr.resolved=!0,sessionStorage.setItem(hm,i.user_id),i.usage_count!==void 0){const n=Gt(),o=i.usage_month||n,a=o===n?i.usage_count:0,l=ba(),u=l.month===n?l.count:0;(a>=u||o>l.month)&&localStorage.setItem(ds,JSON.stringify({count:a,month:n})),Hi()}console.log(`Identity resolved: ${i.status} (${i.user_id.slice(0,8)}...) usage: ${i.usage_count??"n/a"}`)}catch(t){console.error("resolveIdentity failed:",t)}}function ba(){const t=Gt();try{const e=localStorage.getItem(ds);return e?JSON.parse(e):{count:0,month:t}}catch(e){return console.warn("getUsageData: failed to parse usage storage",{key:ds,month:t,err:e}),localStorage.removeItem(ds),{count:0,month:t}}}function Gt(){const t=new Date;return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}`}function Ui(){const t=ba();return t.month!==Gt()?{count:0,month:Gt()}:t}function xv(){const e={count:Ui().count+1,month:Gt()};return localStorage.setItem(ds,JSON.stringify(e)),e}function Ea(){return!!fe.isLoading}function Kt(){return!!fe.isResolved}function kv(t){if(!t)return null;const e=String(t).toLowerCase().replace(/[^a-z0-9]+/g,"_");return e==="pro"||e==="professional_plan"?"professional":e==="power_developer"||e==="power_plan"?"power":Object.prototype.hasOwnProperty.call(mi,e)?e:null}function Iv(t){var e;return t&&((e=Object.entries(xd).find(([,s])=>s===t))==null?void 0:e[0])||null}function Fr(...t){return t.find(e=>e!=null&&e!=="")}function Cv(...t){return t.find(e=>e&&typeof e=="object")||{}}function Fv(t){var c,d,h,p,f,g,v,_,w,S,k,x,P,M,E,A,$,N,T,O;const e=t.data&&typeof t.data=="object"?t.data:t,s=Cv(e.subscription,e.stripeSubscription,e.currentSubscription,(h=(d=(c=e.customer)==null?void 0:c.subscriptions)==null?void 0:d.data)==null?void 0:h[0],(f=(p=e.subscriptions)==null?void 0:p.data)==null?void 0:f[0],(g=e.subscriptions)==null?void 0:g[0]),r=e.metadata||s.metadata||((v=e.customer)==null?void 0:v.metadata)||{},i=Fr(e.priceId,e.price_id,e.stripePriceId,e.stripe_price_id,s.priceId,s.price_id,(_=s.plan)==null?void 0:_.id,(w=s.price)==null?void 0:w.id,(P=(x=(k=(S=s.items)==null?void 0:S.data)==null?void 0:k[0])==null?void 0:x.price)==null?void 0:P.id,(A=(E=(M=s.items)==null?void 0:M[0])==null?void 0:E.price)==null?void 0:A.id,(O=(T=(N=($=s.lines)==null?void 0:$.data)==null?void 0:N[0])==null?void 0:T.price)==null?void 0:O.id),n=Fr(e.status,e.subscriptionStatus,e.subscription_status,s.status,"none"),o=kv(Fr(e.tier,e.plan,e.planId,e.plan_id,e.subscriptionTier,e.subscription_tier,e.product,e.productName,s.tier,s.plan,r.tier,r.plan)),a=fm.has(String(n).toLowerCase()),l=e.active===!0||e.isSubscribed===!0||e.subscribed===!0||e.hasSubscription===!0,u=o||Iv(i)||(a||l?"professional":"free");return bs({tier:u,status:n,periodEnd:Fr(e.periodEnd,e.currentPeriodEnd,e.current_period_end,s.current_period_end,s.periodEnd,null),isResolved:!0})}function Sa(){return mi[fe.tier]??mi.free}async function Pv(){if(q.isVerified&&(!Kt()||Ea())&&(await zd({force:!0}),Wi()),q.isVerified&&!Kt())return ue("Could not verify your subscription. Please refresh or try Manage billing.","error"),!1;const{count:t}=Ui(),e=Sa();if(t>=e)return xa(t,e,{openModal:!0}),!1;const s=Math.floor(e*.8);if(t>=s){const r=e-t;ue(`${r} run${r===1?"":"s"} remaining this month.`,"warning")}return!0}function In(){const t=document.getElementById("paywall-exhausted");t&&t.classList.add("hidden")}function xa(t,e,s={}){const r=document.getElementById("walkthrough-modal");r&&r.classList.remove("open");const i=document.getElementById("ready-state");i&&i.classList.add("hidden");const n=document.getElementById("preview-frame-container");n&&(n.style.display="none");const o=document.getElementById("main-stage-container");o&&o.classList.add("visible");const a=document.getElementById("results-view");a&&a.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar");const l=document.getElementById("pipeline-progress");l&&l.classList.remove("visible");const u=document.getElementById("paywall-exhausted");if(!u){ue(`You've used all ${e} runs for this month. Upgrade to continue.`,"error"),xi();return}const c=document.getElementById("paywall-exhausted-text");if(c){const h=fe.tier;h==="free"?c.textContent=`You've used all ${e} free generations this month. Upgrade to Pro for 50 generations/month and access to all AI models.`:c.textContent=`You've used all ${e} generations this month on your ${h} plan. Your limit resets next month.`}const d=document.getElementById("paywall-signin-btn");d&&d.classList.toggle("hidden",q.isVerified),u.classList.remove("hidden"),s.openModal&&xi()}function ko(t){return fe.tier==="free"&&Br.includes(t)?nr:t}function Av(){const t=document.getElementById("code-options-content"),e=document.getElementById("code-generator-model");if(!t||!e)return;const s=fe.tier,i=!(q.isVerified&&!Kt())&&s==="free";Array.from(e.options).forEach(o=>{const a=Wt(o.value),l=Br.includes(o.value);o.textContent=l&&i?`${a} (PRO)`:a,o.disabled=!1}),i&&Br.includes(e.value)&&(e.value=nr),e.disabled=!1,rc.has(e)||(e.addEventListener("change",()=>{Kt()&&fe.tier==="free"&&Br.includes(e.value)&&(e.value=nr,xi()),So(e.value),Id()}),rc.add(e));let n=document.getElementById("model-selector-free-notice");i?(n||(n=document.createElement("p"),n.id="model-selector-free-notice",n.className="text-xs text-gray-400 mt-1",t.appendChild(n)),n.innerHTML='Free plan — Gemini only. '):n&&n.remove(),So(e.value)}function Hi(){const t=document.getElementById("usage-counter");if(!t)return;if(q.isVerified&&Ea()){t.textContent="Checking plan…",t.className="text-xs text-gray-500",Hr(),In();return}if(q.isVerified&&!Kt()){t.textContent="Plan check failed",t.className="text-xs text-red-600 font-medium",Hr(),In();return}const{count:e}=Ui(),s=Sa();t.textContent=`${e} / ${s} runs this month`;const r=s>0?e/s:0;t.className=r>=1?"text-xs text-red-600 font-medium":r>=.8?"text-xs text-yellow-600 font-medium":"text-xs text-gray-500",Hr(),e>=s&&!y.isRunning?xa(e,s):In()}function Hr(){const t=document.getElementById("guest-usage-text");if(!t)return;const e=ba(),s=e.month===Gt()?e.count??0:0,r=mi.free;t.textContent=`${s} / ${r} generations used`}async function zd(t={}){const e=t.force===!0;if(!q.isVerified||!q.sessionToken){fe=bs({isResolved:!0});return}fe={...fe,isLoading:!0,error:null};const s=localStorage.getItem(vi);if(!e&&s)try{const{data:r,email:i,ts:n,version:o}=JSON.parse(s);if(o===ic&&i===q.email&&Date.now()-n<5*60*1e3){fe={...r,isLoading:!1,isResolved:r.isResolved!==!1};return}}catch(r){console.warn("Failed to parse subscription cache:",r,"| raw value:",s)}try{const i=await(await fetch(`${Ke}/stripe/get-subscription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken,email:q.email})})).json();if(i.error){if(["unauthorized","invalid session","expired session"].some(o=>String(i.error).toLowerCase().includes(o))){_a(),wa();return}fe=bs({isResolved:!1,error:i.error});return}fe=Fv(i),localStorage.setItem(vi,JSON.stringify({version:ic,data:fe,email:q.email,ts:Date.now()}))}catch(r){console.error("fetchSubscription failed:",r),fe={...fe,isLoading:!1,isResolved:!1,error:r.message}}}function ka(){localStorage.removeItem(vi)}async function $v(t){if(!q.isVerified||!q.sessionToken){qd(),ya();return}if(!xd[t]){ue("Invalid plan selected.","error");return}const e=document.getElementById(`checkout-btn-${t}`);e&&(e.disabled=!0,e.textContent="Redirecting…");try{const r=await(await fetch(`${Ke}/stripe/create-checkout-session-intl`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tierId:t,sessionToken:q.sessionToken,currency:Pd()})})).json();if(r.error||!r.url)throw new Error(r.error||"Failed to create checkout session");const{url:i}=r;window.location.href=i}catch(s){console.error("startCheckout failed:",s),e&&(e.disabled=!1,e.textContent="Subscribe"),ue("Could not start checkout. Please try again.","error")}}async function Rv(){if(!q.isVerified||!q.sessionToken){ya();return}const t=document.getElementById("manage-billing-btn");t&&(t.disabled=!0,t.textContent="Loading…");try{const s=await(await fetch(`${Ke}/stripe/create-portal-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:q.sessionToken})})).json();if(s.error||!s.url)throw new Error(s.error||"Failed to open billing portal");const{url:r}=s;window.location.href=r}catch(e){console.error("openCustomerPortal failed:",e),t&&(t.disabled=!1,t.textContent="Manage billing"),ue("Could not open billing portal. Please try again.","error")}}async function Si(t,e,s,r={},i=[]){const o=new AbortController,a=setTimeout(()=>o.abort(),12e4);try{const l=await fetch(dm,{method:"POST",headers:{"Content-Type":"application/json"},signal:o.signal,body:JSON.stringify({user_id:Lr.userId,step:t,model:e,prompt:s,images:i,context:r})}),u=await l.text();let c={};try{c=u?JSON.parse(u):{}}catch{c={}}if(l.status===429){c.serverCount!==void 0&&(localStorage.setItem(ds,JSON.stringify({count:c.serverCount,month:Gt()})),Hi());const p=new Error(c.message||"Monthly usage limit reached. Upgrade to continue.");throw p.isUsageLimit=!0,p}const d=Lf(c,t);if(d)throw d;if(console.log(`[BuildShip] ${t} response keys:`,Object.keys(c),"content type:",typeof c.content),!l.ok)throw new Error(`${c.message||c.error||"BuildShip pipeline error"} (HTTP ${l.status})`);let h=c.output||c.content;if(!h){const p=u?` (body: ${u.slice(0,120)})`:"";throw new Error(`BuildShip returned no output for step "${t}"${p}`)}return Array.isArray(h)&&(h=h.map(p=>typeof p=="string"?p:p.text||"").join("")),typeof h!="string"&&(h=JSON.stringify(h)),h}catch(l){throw l.name==="AbortError"?new Error(`BuildShip ${t} timed out after ${12e4/1e3}s`):l instanceof TypeError?new Error(`BuildShip unreachable: ${l.message}`):l}finally{clearTimeout(a)}}function Tv(){const e=new URLSearchParams(window.location.search).get("checkout");e==="success"?(window.history.replaceState({},"",window.location.pathname),ka(),ue("Subscription active! Welcome aboard.","success")):e==="cancel"&&(window.history.replaceState({},"",window.location.pathname),ue("Checkout cancelled.","info"))}function Wi(){const t=q.isVerified&&!!q.email,e=fe.tier,s=t&&Ea(),r=!t||Kt(),i=document.getElementById("subscription-tier-badge");if(i){const a={free:"Free",professional:"Professional",power:"Power Developer"},l={free:"bg-gray-100 text-gray-600",professional:"bg-indigo-100 text-indigo-700",power:"bg-purple-100 text-purple-700",unresolved:"bg-red-50 text-red-600"};i.textContent=s?"Checking…":r?a[e]||"Free":"Plan unavailable",i.className=`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${r?l[e]||l.free:l.unresolved}`}const n=document.getElementById("upgrade-prompt");n&&n.classList.toggle("hidden",!t||s||!r||e!=="free");const o=document.getElementById("manage-billing-btn");o&&o.classList.toggle("hidden",!t||s||r&&e==="free"),Nv(r?e:null),Av(),Id(),Hi()}function Nv(t){const e=["bg-gray-100","text-gray-500","cursor-default"];Object.entries({professional:{btnId:"checkout-btn-professional",defaultText:"Subscribe"},power:{btnId:"checkout-btn-power",defaultText:"Subscribe"}}).forEach(([i,{btnId:n,defaultText:o}])=>{const a=document.getElementById(n);a&&(i===t?(a.disabled=!0,a.textContent="Current plan",a.classList.add(...e)):(a.disabled=!1,a.textContent=o,a.classList.remove(...e)))});const r=document.getElementById("free-tier-current");r&&r.classList.toggle("hidden",t!=="free")}function Io(){const t=Pd(),e=document.getElementById("pro-price"),s=document.getElementById("power-price"),r=document.getElementById("pro-price-note"),i=document.getElementById("power-price-note");e&&(e.textContent=oc(nc.professional,t)),s&&(s.textContent=oc(nc.power,t));const n="billed monthly";r&&(r.textContent=n),i&&(i.textContent=n)}function xi(){Io();const t=document.getElementById("pricing-modal");t&&t.classList.add("open"),Sm().then(()=>Io())}function qd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("pricing-modal");e&&e.classList.remove("open")}function ue(t,e="info"){const s={success:"bg-green-600 text-white",error:"bg-red-600 text-white",warning:"bg-amber-500 text-white",info:"bg-gray-800 text-white"},r=document.createElement("div");r.className=`fixed bottom-6 left-1/2 -translate-x-1/2 px-5 py-3 rounded-lg text-sm font-medium shadow-lg z-50 transition-opacity duration-300 ${s[e]||s.info}`,r.textContent=t,document.body.appendChild(r),setTimeout(()=>{r.style.opacity="0",setTimeout(()=>r.remove(),300)},3500)}document.addEventListener("DOMContentLoaded",async()=>{hljs.configure({tabReplace:" ",classPrefix:"hljs-"}),Mv(),await yv(),Tv(),await zd(),Wi(),Io(),await Km(),Wm();const t=document.getElementById("flutterflow-endpoint-select");if(t){const s=ur();t.value=s}Md(),Sv();const e=document.getElementById("pipeline-input");e&&(e.addEventListener("input",()=>{bt===2&&e.value.trim().length>0&&(oa(),Ti())}),e.addEventListener("blur",()=>{const s=document.getElementById("walkthrough-modal");bt===2&&s&&s.classList.add("open")}),e.addEventListener("keydown",s=>{if(s.key==="Tab"){const r=document.getElementById("walkthrough-modal");bt===2&&r&&setTimeout(()=>{r.classList.add("open")},100)}})),window.addEventListener("commitStateChange",s=>{const{state:r}=s.detail;r===G.PREPARING||r===G.VALIDATING||r===G.PUSHING?(be.phaseId||Kd(),gc(r)):(r===G.SUCCESS||r===G.ERROR)&&(gc(r),setTimeout(ki,1e3))})});function Mv(){const t=document.getElementById("preview-frame-container");t&&(t.style.display="")}function Ov(){const t=document.getElementById("welcome-video-player");t&&(t.addEventListener("click",Jt),document.addEventListener("keydown",Jt))}function Jt(){const t=document.getElementById("preview-frame-container"),e=document.getElementById("main-stage-container"),s=document.getElementById("ready-state");t&&(t.style.display="none"),e&&e.classList.add("visible"),s&&s.classList.remove("hidden");const r=document.getElementById("welcome-video-player");r&&r.removeEventListener("click",Jt),document.removeEventListener("keydown",Jt),Md()}let Ys=null;async function Lv(){const t=document.getElementById("confirm-project-select");if(!t)return;const e=++dc,s=()=>e===dc,r=await Ee("flutterflow"),i=await Ee("flutterflow_project_id");if(s()){if(!r){t.innerHTML='',t.disabled=!0;return}t.disabled=!1,t.innerHTML='';try{const o=await new dr(r,"").listProjects();if(!s())return;if(!o||o.length===0){t.innerHTML='';return}t.innerHTML='',o.forEach(a=>{const l=document.createElement("option");l.value=a.id||a.projectId||"",l.textContent=a.name||a.projectName||`Project ${a.id}`,t.appendChild(l)}),i&&(t.value=i)}catch(n){if(!s())return;console.error("Failed to load projects for deploy:",n),t.innerHTML=''}}}function Bv(){var s;const t=document.getElementById("confirm-project-select");return((s=t==null?void 0:t.value)==null?void 0:s.trim())||null}function Vd(t,e,s,r=null){Ys={codeInfo:t,checks:e,deps:s,bundlePlan:r},document.getElementById("confirm-file-name").textContent=t.fileName,document.getElementById("confirm-artifact-type").textContent=t.artifactType,document.getElementById("confirm-file-size").textContent=`${(t.content.length/1024).toFixed(1)} KB`,document.getElementById("confirm-line-count").textContent=r?`${r.fileEntries.length} files`:t.content.split(` +`).length,Lv();const i=document.getElementById("confirm-deps-list"),n=document.getElementById("confirm-deps-section");s&&Object.keys(s).length>0?(i.innerHTML=Object.entries(s).map(([u,c])=>{const d=c?`at least ${wt(c)}`:"version resolved from your project";return`
  • • ${wt(u)}: ${d}
  • `}).join(""),n.classList.remove("hidden")):n.classList.add("hidden");const o=document.getElementById("confirm-warnings-list"),a=document.getElementById("confirm-warnings-section");e.warnings&&e.warnings.length>0?(o.innerHTML=e.warnings.map(u=>`
  • • ${wt(u)}
  • `).join(""),a.classList.remove("hidden")):a.classList.add("hidden"),document.getElementById("confirm-code-preview").textContent=t.content,document.getElementById("code-preview-content").classList.add("hidden"),document.getElementById("code-preview-chevron").style.transform="rotate(0deg)";const l=document.getElementById("commit-confirm-modal");l&&l.classList.add("open")}function Gd(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-confirm-modal");e&&e.classList.remove("open"),Ys=null}function Dv(t){if(t&&t.target!==t.currentTarget)return;const e=document.getElementById("commit-success-modal");e&&e.classList.remove("open");const s=["success-message","success-project-id","success-file-name","success-artifact-type","success-time","success-size"];for(const n of s){const o=document.getElementById(n);o&&(o.textContent="")}const r=document.getElementById("success-warnings-section");r&&r.classList.add("hidden");const i=document.getElementById("success-warnings-list");i&&(i.innerHTML="")}function Co(t){var p,f,g,v;const e=(_,w)=>{const S=document.getElementById(_);S&&(S.textContent=w||"")},s=((p=t.metadata)==null?void 0:p.fileName)||"",r=((f=t.metadata)==null?void 0:f.projectId)||"",i=((g=t.metadata)==null?void 0:g.artifactType)||"",n=t.elapsedTime?`${(t.elapsedTime/1e3).toFixed(1)}s`:"",o=(v=t.metadata)!=null&&v.codeSize?`${(t.metadata.codeSize/1024).toFixed(1)} KB`:"";e("success-message",t.message||"Code committed successfully!"),e("success-project-id",r),e("success-file-name",s),e("success-artifact-type",i),e("success-time",n),e("success-size",o);const a=t.addedDependencies||[],l=document.getElementById("success-deps-row");l&&l.classList.toggle("hidden",a.length===0),e("success-deps",a.join(", "));const u=document.getElementById("success-open-ff-link");u&&r&&(u.href=`https://app.flutterflow.io/project/${r}`);const c=document.getElementById("success-warnings-section"),d=document.getElementById("success-warnings-list");t.warnings&&t.warnings.length>0&&c&&d&&(d.innerHTML=t.warnings.map(([_,w])=>`
  • ${j(_)}: ${j(String(w))}
  • `).join(""),c.classList.remove("hidden"));const h=document.getElementById("commit-success-modal");h&&h.classList.add("open")}function Fo(t){ki(),pv(t)}function jv(){const t=document.getElementById("code-preview-content"),e=document.getElementById("code-preview-chevron");t.classList.contains("hidden")?(t.classList.remove("hidden"),e.style.transform="rotate(90deg)"):(t.classList.add("hidden"),e.style.transform="rotate(0deg)")}const fc={prepare:{message:"Preparing your code...",start:4,end:14},validate:{message:"Checking FlutterFlow credentials...",start:14,end:22},project:{message:"Reading your FlutterFlow project...",start:22,end:40},provision:{message:"Creating custom classes in FlutterFlow...",start:40,end:82},package:{message:"Packaging files for upload...",start:82,end:88},push:{message:"Pushing to FlutterFlow...",start:88,end:97},done:{message:"Complete!",start:100,end:100}},Uv=[{after:0,text:"Starting a FlutterFlow build runner..."},{after:12,text:"Preparing the FlutterFlow AI workspace..."},{after:35,text:"Uploading your custom classes..."},{after:60,text:"FlutterFlow is applying the changes..."},{after:100,text:"Still working — this can take a couple of minutes..."}],be={sequence:[],phaseId:null,phaseStartedAt:null,timer:null,substatus:null,liveSubstatus:!1,start({withProvisioning:t=!1}={}){this.sequence=["prepare","validate","project"],t&&this.sequence.push("provision"),this.sequence.push("package","push","done");const e=document.getElementById("commit-progress-overlay");e&&e.classList.add("open"),this.set("prepare")},set(t,e=null){if(!(!fc[t]||t===this.phaseId)){if(!this.sequence.includes(t)){const s=this.sequence.indexOf("package");this.sequence.splice(s===-1?this.sequence.length:s,0,t)}this.phaseId=t,this.phaseStartedAt=Date.now(),this.substatus=e,this.liveSubstatus=!1,this.render(),this.timer&&clearInterval(this.timer),t!=="done"&&(this.timer=setInterval(()=>this.render(),500))}},setSubstatus(t){t&&(this.liveSubstatus=!0,this.substatus=t,this.render())},render(){const t=fc[this.phaseId];if(!t)return;const e=(Date.now()-this.phaseStartedAt)/1e3,s=t.start+(t.end-t.start)*(1-Math.exp(-e/25));if(this.phaseId==="provision"&&!this.liveSubstatus){const o=Uv.filter(a=>e>=a.after).pop();o&&(this.substatus=o.text)}const r=this.sequence.indexOf(this.phaseId),n=[`Step ${r===-1?1:r+1} of ${this.sequence.length}`];e>=5&&n.push(Hv(e)),Jd(this.phaseId==="done"?100:s,t.message,n.join(" · "),this.substatus)},stop(){this.timer&&clearInterval(this.timer),this.timer=null,this.phaseId=null;const t=document.getElementById("commit-progress-overlay");t&&t.classList.remove("open")}};function Hv(t){const e=Math.floor(t);return e<60?`${e}s elapsed`:`${Math.floor(e/60)}m ${String(e%60).padStart(2,"0")}s elapsed`}function Kd(t){be.start(t)}function ki(){be.stop()}function Jd(t,e,s,r=null){const i=document.getElementById("commit-progress-bar"),n=document.getElementById("progress-message"),o=document.getElementById("progress-detail"),a=document.getElementById("progress-substatus");i&&(i.style.width=`${Math.round(t*10)/10}%`),n&&(n.textContent=e),o&&(o.textContent=s),a&&(a.textContent=r||"",a.classList.toggle("hidden",!r))}function gc(t){const e={[G.PREPARING]:"prepare",[G.VALIDATING]:"validate",[G.PUSHING]:"project",[G.SUCCESS]:"done"};if(t===G.ERROR){be.timer&&clearInterval(be.timer),be.timer=null,Jd(100,"Failed","Error occurred");return}const s=e[t];s&&be.set(s)}function Wv(t){var e;return t.bundlePlan?t.bundlePlan.fileEntries.some(s=>s.type===U.CODE_FILE):((e=t.codeInfo)==null?void 0:e.codeType)===U.CODE_FILE}async function zv(){var o,a;if(!Ys){console.error("No pending commit data");return}const t=Ys;if(Ys=null,Js=Bv(),Gd(),Kd({withProvisioning:Wv(t)}),t.bundlePlan){const l=await sv(t.bundlePlan,{pipelineResult:{step1Result:y.step1Result,selectedModel:(o=document.getElementById("code-generator-model"))==null?void 0:o.value}});Js=null,ki(),l.success?Co(l):Fo(l);return}const{codeInfo:e}=t,{artifactType:s,artifactName:r,fileName:i}=Ld(),n=await tv(e.content,{artifactType:s,artifactName:r,fileName:i,pipelineResult:{step1Result:y.step1Result,selectedModel:(a=document.getElementById("code-generator-model"))==null?void 0:a.value}});Js=null,ki(),n.success?Co(n):Fo(n)}window.runThinkingPipeline=xo;window.toggleStep=nv;window.toggleSection=iv;window.selectWorkflowStep=ze;window.copyCode=ov;window.retryWithDifferentModel=uv;window.openApiKeysModal=na;window.closeApiKeysModal=Td;window.closeWalkthroughModal=Lm;window.openWalkthroughModal=Om;window.advanceWalkthrough=oa;window.commitToFlutterFlow=ev;function qv(){const t=document.getElementById("pipeline-input");t&&t.focus()}function Vv(){const t=document.getElementById("advanced-settings");t&&(t.open=!0);const e=document.getElementById("code-generator-model");e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.focus(),e.click())}window.focusPromptInput=qv;window.openModelSelector=Vv;window.handlePromptImageSelect=bm;window.removePromptImage=Em;window.saveApiKeys=jm;window.clearAllApiKeys=Um;window.toggleKeyVisibility=qm;window.handleWelcomeVideoEnd=Ov;window.dismissWelcomeVideo=Jt;window.initiateCommitToFlutterFlow=dv;window.updateFlutterFlowCredentialStatus=gv;window.closeCommitConfirmModal=Gd;window.closeCommitSuccessModal=Dv;window.showCommitSuccessModal=Co;window.showCommitFailureModal=Fo;window.toggleCodePreview=jv;window.confirmCommitToFlutterFlow=zv;window.runRefinement=av;window.regenerateFromPastedErrors=cv;window.clearErrorInput=lv;window.setFlutterFlowEndpoint=Mm;window.getFlutterFlowEndpoint=ur;window.commitProgress=be;window.openSignInModal=ya;window.closeSignInModal=wv;window.handleMagicLinkRequest=bv;window.handleSignOut=Ev;window.startCheckout=$v;window.openCustomerPortal=Rv;window.openPricingModal=xi;window.closePricingModal=qd;let hs=null,Yd=null;const mc=120;function zi(){const t=document.getElementById("pipeline-progress"),e=document.getElementById("results-view"),s=document.getElementById("ready-state");s&&s.classList.add("hidden"),e&&e.classList.remove("visible"),document.body.classList.remove("results-fullscreen","results-with-sidebar"),t&&t.classList.add("visible"),Yd=Date.now();for(let r=1;r<=3;r++){const i=document.getElementById(`pdot-${r}`);i&&(i.className="progress-dot")}rt(1),Gv()}function rt(t){const e={1:"Analyzing your prompt...",2:"Generating Dart code...",3:"Running code audit..."},s={1:"Step 1 of 3 — Prompt Architect",2:"Step 2 of 3 — Code Generator",3:"Step 3 of 3 — Code Review"},r=document.getElementById("progress-title-text"),i=document.getElementById("progress-substep-text");r&&(r.textContent=e[t]||e[1]),i&&(i.textContent=s[t]||s[1]);for(let n=1;n<=3;n++){const o=document.getElementById(`pdot-${n}`);o&&(n{const t=(Date.now()-Yd)/1e3,e=document.getElementById("progress-elapsed"),s=document.getElementById("pipeline-progress-fill");e&&(e.textContent=`${Math.floor(t)}s`);const r=t/mc*100,i=Math.min(95,r*(1-Math.exp(-t/(mc*.6)))*1.2);s&&(s.style.width=`${i}%`)},250)}function Pt(){hs&&(clearInterval(hs),hs=null);const t=document.getElementById("pipeline-progress-fill");t&&(t.style.width="100%");for(let e=1;e<=3;e++){const s=document.getElementById(`pdot-${e}`);s&&(s.className="progress-dot completed")}setTimeout(()=>{const e=document.getElementById("pipeline-progress");e&&e.classList.remove("visible"),t&&(t.style.width="0%")},400)}function Ss(t,e=""){const s={pass:'',warning:'',fail:'',info:''};return``}function Zd(t){return{pass:"Passed review",warning:"Needs attention",fail:"Blocking issues"}[t]||"Needs attention"}function Kv(){return Pg({bundle:y.artifactBundle,reviewResult:y.step3Result})}function Jv(t){return`
    ${Ss(t.severity)}
    @@ -179,14 +189,14 @@ Error: ${h} ${j(t.source)}
    - `}function Bv(t){return` + `}function Yv(t){return`
  • ${j(t.title)} ${t.detail&&t.detail!==t.title?`

    ${j(t.detail)}

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

      ${j(d.reason)}

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

      ${j(d.description)}

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

      ${j(e.artifactName)}

      ${e.description?`

      ${j(e.description)}

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

      Manual FlutterFlow steps for this file

      -
        ${e.manualSteps.map(Bv).join("")}
      +
        ${e.manualSteps.map(Yv).join("")}
      `:""}
      @@ -293,12 +303,12 @@ Error: ${h}
        ${a}
      - `}function Uv(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),i=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){i&&(i.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(i){const n=t.artifacts.length;i.textContent=`${n} ${n===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(n=>` + `}function Qv(t){const e=document.getElementById("bundle-strip"),s=document.getElementById("results-summary-tab"),r=document.getElementById("artifact-tabs"),i=document.getElementById("results-file-count");if(s&&s.classList.toggle("active",y.resultsViewMode==="summary"),!t.artifacts.length){i&&(i.textContent="0 files"),e&&e.classList.remove("visible"),r&&(r.innerHTML="");return}if(i){const n=t.artifacts.length;i.textContent=`${n} ${n===1?"file":"files"}`}r&&(r.innerHTML=t.artifacts.map(n=>` - `).join(""),r.onclick=n=>{var a;const o=n.target.closest(".artifact-tab");(a=o==null?void 0:o.dataset)!=null&&a.artifactId&&Gd(o.dataset.artifactId)}),e&&e.classList.add("visible")}function xa(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),i=document.getElementById("artifact-results-split"),n=Ov(),o=aa();if(Dv(n),Uv(n),e&&(e.textContent=""),e){const a=_d(o);e.innerHTML=a}s&&(s.innerHTML=jv(n)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),i&&i.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function zi(t,e){y.selectedArtifactId||(y.selectedArtifactId=di(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),xa(),Yt();const r=document.getElementById("btn-feedback-up"),i=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),i&&(i.className="feedback-btn")}function Gd(t){y.selectedArtifactId=t,y.resultsViewMode="file",xa()}function Hv(){y.resultsViewMode="summary",xa()}function Wv(){const t=document.getElementById("btn-copy-results"),e=aa();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function zv(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up"));const r=t==="up"?"thumbsUp":"thumbsDown";ga(r,y.step2Result,y.step1Result),Ht("Generation Feedback",{feedback:r})}function qv(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Kd(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=Wv;window.selectArtifact=Gd;window.selectResultsSummary=Hv;window.submitResultsFeedback=zv;window.showErrorInputPanel=qv;window.hideErrorInputPanel=Kd; + `).join(""),r.onclick=n=>{var a;const o=n.target.closest(".artifact-tab");(a=o==null?void 0:o.dataset)!=null&&a.artifactId&&Xd(o.dataset.artifactId)}),e&&e.classList.add("visible")}function Ia(){document.body.classList.add("results-fullscreen"),document.body.classList.add("results-with-sidebar");const t=document.getElementById("results-view"),e=document.getElementById("results-code-output"),s=document.getElementById("results-audit-output"),r=document.getElementById("results-summary-detail"),i=document.getElementById("artifact-results-split"),n=Kv(),o=ca();if(Zv(n),Qv(n),e&&(e.textContent=""),e){const a=Sd(o);e.innerHTML=a}s&&(s.innerHTML=Xv(n)),r&&r.classList.toggle("hidden",y.resultsViewMode!=="summary"),i&&i.classList.toggle("hidden",y.resultsViewMode!=="file"),t&&t.classList.add("visible")}function qi(t,e){y.selectedArtifactId||(y.selectedArtifactId=hi(y.artifactBundle).id),y.resultsViewMode="summary",document.body.classList.add("results-fullscreen");const s=document.getElementById("step3-output");s&&(s.textContent=""),Ia(),Yt();const r=document.getElementById("btn-feedback-up"),i=document.getElementById("btn-feedback-down");r&&(r.className="feedback-btn"),i&&(i.className="feedback-btn")}function Xd(t){y.selectedArtifactId=t,y.resultsViewMode="file",Ia()}function e_(){y.resultsViewMode="summary",Ia()}function t_(){const t=document.getElementById("btn-copy-results"),e=ca();navigator.clipboard.writeText(e).then(()=>{if(t){t.classList.add("copied");const s=t.querySelector("span");if(s){const r=s.textContent;s.textContent="Copied!",setTimeout(()=>{t.classList.remove("copied"),s.textContent=r},2e3)}}})}function s_(t){const e=document.getElementById("btn-feedback-up"),s=document.getElementById("btn-feedback-down");t==="up"?(e.classList.toggle("active-up"),s.classList.remove("active-down")):(s.classList.toggle("active-down"),e.classList.remove("active-up"));const r=t==="up"?"thumbsUp":"thumbsDown";va(r,y.step2Result,y.step1Result),Ht("Generation Feedback",{feedback:r})}function r_(){const t=document.getElementById("error-input-panel");if(t){t.classList.remove("hidden"),t.style.display="flex";const e=document.getElementById("ff-error-paste-input");e&&setTimeout(()=>e.focus(),100)}}function Qd(){const t=document.getElementById("error-input-panel");t&&(t.classList.add("hidden"),t.style.display="none")}window.copyResultsCode=t_;window.selectArtifact=Xd;window.selectResultsSummary=e_;window.submitResultsFeedback=s_;window.showErrorInputPanel=r_;window.hideErrorInputPanel=Qd; diff --git a/dist/index.html b/dist/index.html index e5f80ec..c805f3f 100644 --- a/dist/index.html +++ b/dist/index.html @@ -2420,7 +2420,7 @@ .pm-cards { padding: 0 16px; } } - +
      diff --git a/src/flutterFlowArtifactValidation.js b/src/flutterFlowArtifactValidation.js index b0649e1..0ed5f40 100644 --- a/src/flutterFlowArtifactValidation.js +++ b/src/flutterFlowArtifactValidation.js @@ -461,7 +461,7 @@ export function getCustomClassFileNameError(fileName, code) { * @param {string} name - Dart identifier, e.g. "initQAAnalytics" * @returns {string} File stem, e.g. "init_q_a_analytics" */ -function identifierToFlutterFlowFileStem(name) { +export function identifierToFlutterFlowFileStem(name) { return String(name || "") .replace(/([A-Z])/g, "_$1") .toLowerCase() diff --git a/src/flutterFlowCodeSanitizer.js b/src/flutterFlowCodeSanitizer.js new file mode 100644 index 0000000..f204627 --- /dev/null +++ b/src/flutterFlowCodeSanitizer.js @@ -0,0 +1,453 @@ +import { deriveIdentifierName } from "./flutterFlowSyncMetadata.js"; +import { identifierToFlutterFlowFileStem } from "./flutterFlowArtifactValidation.js"; + +// LLM responses routinely arrive wrapped in markdown code fences, with a BOM, +// or with prose before/after the Dart. FlutterFlow's push-time formatter +// rejects any of that with "Custom widget code is not formattable", so it must +// be stripped before the code is validated or committed. +const BOM_PATTERN = /^\uFEFF/; + +function trimBlankEdgeLines(lines) { + let start = 0; + let end = lines.length; + + while (start < end && !lines[start].trim()) start++; + while (end > start && !lines[end - 1].trim()) end--; + + return lines.slice(start, end).join("\n"); +} + +/** + * Removes markdown artifacts and surrounding junk from generated Dart. + * + * Fence recognition is phase-separated. Phase one is purely structural: a + * fence marker is a line containing nothing but three-or-more backticks and + * an optional info-string tag. Everything before the first accepted opening + * marker and after the last accepted closing marker is markdown prose by + * definition and is NEVER scanned as Dart, so stray tokens in prose (an + * unmatched `/*`, a stray quote) cannot poison recognition and hide later + * code blocks (STU-148). Phase two applies Dart awareness only INSIDE a + * fenced block: a candidate closer is accepted only when the scanner proves + * the marker sits outside every comment/string span of the accumulated + * block content, so literal ``` lines inside triple-quoted strings or + * (nested) block comments survive byte-for-byte (STU-147). + * + * Completed pairs are kept and joined; inter-block prose is dropped. An + * open block at end of input is a truncated response and is dropped: + * committing cut-off Dart fails formatting anyway. With exactly one fence + * line (a truncated wrap), whichever side holds more content is kept. + * Blank edge lines are trimmed so header application downstream starts + * from clean source. + * @param {string} rawCode - Raw generated response text + * @returns {string} Dart-only source, empty when the input has no content + */ +export function sanitizeGeneratedDart(rawCode) { + const code = String(rawCode ?? "").replace(BOM_PATTERN, ""); + if (!code.trim()) return ""; + + const lines = code.split("\n"); + + // Structural candidates only: the trimmed line must be a bare fence + // marker with an optional language tag - nothing else on the line. + const fenceIndent = (line) => { + const trimmed = line.trim(); + return /^`{3,}[A-Za-z0-9+#_.-]*$/.test(trimmed) + ? line.length - line.trimStart().length + : -1; + }; + + let candidates = 0; + let firstCandidate = -1; + const candidateOffsets = []; + { + let lineStartOffset = 0; + for (let index = 0; index < lines.length; index++) { + const indent = fenceIndent(lines[index]); + if (indent >= 0) { + candidates++; + if (firstCandidate < 0) firstCandidate = index; + candidateOffsets.push(lineStartOffset + indent); + } + lineStartOffset += lines[index].length + 1; + } + } + + // No fences: the response is a plain Dart file (possibly padded). + if (candidates === 0) return trimBlankEdgeLines(lines); + + // Plain-Dart interpretation: when the full source scans without a single + // lexical problem AND every candidate marker sits inside a comment/string + // span, none of them is a markdown delimiter - the input is a fence-less + // Dart file whose doc examples happen to contain backtick lines. Return it + // untouched instead of pairing literals as fences (STU-147). The + // error-free requirement keeps prose tokens like a stray `/*` - which + // would swallow every later marker into one phantom comment span - from + // spoofing this branch; genuinely broken responses fall through to + // markdown extraction. + { + const wholeScan = scanDartSource(code); + const allLiteral = + !wholeScan.error && + candidateOffsets.every((offset) => + offsetIsInsideCommentOrString(offset, wholeScan.commentAndStringRanges) + ); + if (allLiteral) return trimBlankEdgeLines(lines); + } + + // Exactly one fence line means a truncated or partial wrap; keep the side + // that actually carries code instead of emitting an empty or doubled file. + if (candidates === 1) { + const before = trimBlankEdgeLines(lines.slice(0, firstCandidate)); + const after = trimBlankEdgeLines(lines.slice(firstCandidate + 1)); + return after.length >= before.length ? after : before; + } + + const segments = []; + let block = null; // accumulated lines of the currently-open fenced block + for (let index = 0; index < lines.length; index++) { + const line = lines[index]; + const indent = fenceIndent(line); + + if (indent < 0) { + if (block) block.push(line); + continue; + } + + if (block === null) { + // Opening fence: acceptance is structural - preceding prose is never + // consulted, so tokens in prose cannot suppress this block. + block = []; + continue; + } + + // Candidate closer inside an open block: accept only when the marker + // sits outside every comment/string span of the block content itself. + // The candidate line is part of the scanned text so an open triple-quoted + // string (whose span runs to end-of-scan) covers the marker position. + const content = block.join("\n"); + const scanText = `${content}\n${line}`; + const { commentAndStringRanges } = scanDartSource(scanText); + const markerOffset = content.length + 1 + indent; + if (offsetIsInsideCommentOrString(markerOffset, commentAndStringRanges)) { + block.push(line); // literal ``` inside the block's own strings/comments + continue; + } + segments.push(trimBlankEdgeLines(block)); + block = null; // closing fence accepted; following prose is dropped + } + // A block still open at EOF is a truncated response: drop it, along with + // all leading/trailing prose outside completed pairs. + + const kept = segments.filter((segment) => segment.length > 0); + if (kept.length === 0) return ""; + + return kept.join("\n\n"); +} + +/** + * Blanks comments and string literal bodies so name detection never matches + * prose. Order matters: block comments first (they may contain // and quotes), + * then line comments, then triple-quoted strings, then ordinary strings. + * @param {string} code - Dart source + * @returns {string} Source with comment/string content removed + */ +function stripCommentsAndStringBodies(code) { + return String(code ?? "") + .replace(/\/\*[\s\S]*?\*\//g, " ") + .replace(/\/\/[^\n]*/g, "") + .replace(/'''[\s\S]*?'''/g, '""') + .replace(/"""[\s\S]*?"""/g, '""') + .replace(/'(?:\\.|[^'\\\n])*'/g, '""') + .replace(/"(?:\\.|[^"\\\n])*"/g, '""'); +} + +/** + * Names of the public widget classes declared in Dart source. FlutterFlow can + * place any public class whose superclass is a Widget - not only a literal + * `StatelessWidget`/`StatefulWidget`: `ConsumerStatefulWidget`, + * `StatelessHookWidget`, and other transitive Widget subclasses place + * normally, so matching "extends Widget" covers them without + * false-rejecting a healthy single-file widget. Private (underscore-prefixed) + * helpers are excluded: FlutterFlow never places them directly. + * @param {string} code - Dart source + * @returns {string[]} Declared public widget class names, in declaration order + */ +export function getDeclaredWidgetClasses(code) { + const stripped = stripCommentsAndStringBodies(code); + return Array.from( + stripped.matchAll(/class\s+([A-Z]\w*)\s+extends\s+[A-Za-z_]\w*Widget\b/g), + (match) => match[1], + ); +} + +/** + * The file name FlutterFlow expects for a widget class: its naive snake_case + * of the identifier (`LiquidGlassOrbs` -> `liquid_glass_orbs.dart`). FF reads + * the widget's identity back out of the committed file name, so this is the + * only name under which the class is findable. + * @param {string} className - Public widget class name + * @returns {string} File name to commit the class under + */ +export function widgetFileNameForClass(className) { + return `${identifierToFlutterFlowFileStem(className)}.dart`; +} + +/** + * The widget class FlutterFlow will look for inside a committed file, derived + * the same way FF derives it - from the file name alone. + * @param {string} fileName - Bare file name, e.g. "liquid_glass_orbs.dart" + * @returns {string} Class name FF resolves, e.g. "LiquidGlassOrbs" + */ +export function expectedWidgetClassFromFileName(fileName) { + return deriveIdentifierName(fileName, "W"); +} + +const OPENERS = { "(": ")", "[": "]", "{": "}" }; +const CLOSERS = { ")": "(", "]": "[", "}": "{" }; +// Identifier characters that disqualify a preceding r/R from starting a raw +// string. `$` is deliberately absent: in `${r'...'}'` the character before +// the prefix can be `$`/`{` interpolation syntax, and treating `$` as an +// identifier tail made valid interpolated raw strings misclassify as +// ordinary strings whose backslash escapes the closing quote (STU-148). +const IDENTIFIER_TAIL = /[A-Za-z0-9_]/; + +/** + * Single lexical pass over Dart source using a frame stack that models + * nesting: top-level code, bracketed regions, comments, strings, and string + * interpolations. It produces two things from one walk: + * + * - `error`: the first bracket-balance problem, or null when brackets balance. + * This is what FlutterFlow's formatter actually fails on - "Custom widget + * code is not formattable" - so catching it client-side turns a cryptic + * post-push rejection into an actionable pre-commit error. + * - `commentAndStringRanges`: character spans occupied by comments and string + * literals (delimiters included). Consumers use these to tell literal Dart + * content apart from structural code - e.g. a ``` marker inside a doc string + * is content, not a markdown fence (STU-147). + * + * The scan tracks comments, string literals, and `${...}` interpolations so + * brackets that belong to strings or docs never count, including nested cases + * like `user['name']` inside an interpolation. Block comments nest the way + * Dart defines them: every inner comment opener raises the depth and only + * enough closers bring the span back to zero, so a lone inner closer cannot + * terminate the comment early (STU-147). Raw strings (`r'...'`, `R'''...'''`) are + * honored: their backslash escapes nothing and they never interpolate, so a + * raw string ending in a backslash closes at its quote instead of being + * misread as an escaped one (STU-148). + * + * Unterminated tokens never pass silently: a string frame still open at EOF, + * or an ordinary string broken by a bare newline (illegal in Dart), is + * reported through `error` with its opening line - triple-quoted strings stay + * legal while open mid-source but error if never closed by EOF (STU-148). + * Tokens still open at end of input have their span closed there, so + * consumers always see the full extent of unterminated strings/comments even + * though the scan flags them. + * @param {string} src - Dart source (any text; never throws) + * @returns {{error: string|null, commentAndStringRanges: Array<{start: number, end: number}>}} + */ +function scanDartSource(src) { + // Frames model nesting: top-level code, bracketed regions, comments, + // strings, and string interpolations. Every frame knows what ends it. + const frames = [{ kind: "code", opener: null, openedLine: 0 }]; + const commentAndStringRanges = []; + let line = 1; + let i = 0; + + // First problem found that does not halt the scan (an unterminated ordinary + // string broken by a newline). The scan keeps walking so ranges and later + // bracket attribution stay correct, but this error still blocks the gate. + let firstError = null; + + // Unterminated tokens still occupy source: close their spans at end of + // input so consumers always see the full extent of any string/comment still + // open when the scan stops - on an error or at EOF alike. + const closeOpenTokenSpans = () => { + for (const frame of frames) { + if ( + frame.kind === "string" + || frame.kind === "block-comment" + || frame.kind === "line-comment" + ) { + commentAndStringRanges.push({ start: frame.startIndex, end: src.length }); + } + } + }; + + while (i < src.length) { + const ch = src[i]; + const frame = frames[frames.length - 1]; + + if (frame.kind === "line-comment") { + if (ch === "\n") { + commentAndStringRanges.push({ start: frame.startIndex, end: i }); + frames.pop(); + } else i++; + continue; + } + + if (frame.kind === "block-comment") { + // Dart block comments nest: each inner /* raises the depth, and the + // comment only ends once enough */ closers bring it back to zero. A + // lone inner closer must not end the span - everything up to the real + // close stays protected content. + if (ch === "*" && src[i + 1] === "/") { + frame.depth--; + if (frame.depth === 0) { + commentAndStringRanges.push({ start: frame.startIndex, end: i + 2 }); + frames.pop(); + } + i += 2; + } else if (ch === "/" && src[i + 1] === "*") { + frame.depth++; + i += 2; + } else { + if (ch === "\n") line++; + i++; + } + continue; + } + + if (frame.kind === "string") { + // A bare newline cannot appear inside a non-triple Dart string: this + // string is unterminated. End its span at the newline so later lines + // still scan (and fence recognition still sees them) but surface the + // break - silently healing used to let malformed source pass the + // pre-commit gate and fail opaquely inside FlutterFlow (STU-148). + if (!frame.triple && ch === "\n") { + commentAndStringRanges.push({ start: frame.startIndex, end: i }); + firstError ??= `line ${line}: string starting on line ${frame.openedLine} is never closed`; + frames.pop(); + continue; + } + if (!frame.raw && ch === "\\") { + // An escaped newline is a line continuation - keep the line count true. + if (src[i + 1] === "\n") line++; + i += 2; + continue; + } + if (!frame.raw && ch === "$" && src[i + 1] === "{") { + frames.push({ kind: "code", opener: null, interpolation: true }); + i += 2; + continue; + } + const closerLength = frame.triple ? 3 : 1; + if ( + ch === frame.quote + && src.slice(i, i + closerLength) === frame.quote.repeat(closerLength) + ) { + commentAndStringRanges.push({ + start: frame.startIndex, + end: i + closerLength, + }); + frames.pop(); + i += closerLength; + continue; + } + if (ch === "\n") line++; + i++; + continue; + } + + // --- code frame --- + if (ch === "/" && src[i + 1] === "/") { + frames.push({ kind: "line-comment", startIndex: i }); + i += 2; + continue; + } + if (ch === "/" && src[i + 1] === "*") { + frames.push({ kind: "block-comment", startIndex: i, openedLine: line, depth: 1 }); + i += 2; + continue; + } + if (ch === "'" || ch === '"') { + const triple = src.slice(i, i + 3) === ch.repeat(3); + // r'...' / R'''...''' are raw strings: the r must not be the tail of a + // longer identifier, or `var bar'` style code would misclassify. + const prev = i > 0 ? src[i - 1] : ""; + const beforePrev = i > 1 ? src[i - 2] : ""; + const raw = + (prev === "r" || prev === "R") && !IDENTIFIER_TAIL.test(beforePrev); + frames.push({ kind: "string", quote: ch, triple, raw, startIndex: i, openedLine: line }); + i += triple ? 3 : 1; + continue; + } + if (OPENERS[ch]) { + frames.push({ kind: "code", opener: ch, openedLine: line }); + i++; + continue; + } + if (CLOSERS[ch]) { + if (frame.interpolation && ch === "}") { + frames.pop(); + i++; + continue; + } + if (frame.opener && OPENERS[frame.opener] === ch) { + frames.pop(); + i++; + continue; + } + if (frame.opener) { + closeOpenTokenSpans(); + return { + error: firstError + ?? `line ${line}: "${ch}" closes nothing - "${frame.opener}" opened on line ${frame.openedLine} is still open`, + commentAndStringRanges, + }; + } + // A closer can never legitimately reach an interpolation or top-level + // frame: whatever it closes would have to sit above it in the stack. + closeOpenTokenSpans(); + return { + error: firstError ?? `line ${line}: unexpected "${ch}" with no matching opener`, + commentAndStringRanges, + }; + } + if (ch === "\n") line++; + i++; + } + + closeOpenTokenSpans(); + + let error = firstError; + if (!error) { + const remaining = frames[frames.length - 1]; + if (!(remaining.kind === "code" && !remaining.opener && !remaining.interpolation)) { + if (remaining.kind === "string") { + error = `unclosed ${remaining.triple ? "triple-quoted " : ""}string starting on line ${remaining.openedLine} was never closed`; + } else if (remaining.kind === "block-comment") { + error = `unterminated /* comment starting on line ${remaining.openedLine}`; + } else if (remaining.kind === "line-comment") { + error = null; // Ends at end-of-input by definition. + } else if (remaining.interpolation) { + const openerFrame = frames.findLast((f) => f.opener); + const where = openerFrame ? ` opened on line ${openerFrame.openedLine}` : ""; + error = `unclosed "\${" expression${where} was never closed`; + } else { + error = `"${remaining.opener}" opened on line ${remaining.openedLine} is never closed`; + } + } + } + + return { error, commentAndStringRanges }; +} + +/** + * Reports the first bracket-balance problem in Dart source, or null when the + * brackets balance. See scanDartSource for the lexical rules. + * @param {string} code - Dart source + * @returns {string|null} Precise error message, or null when balanced + */ +export function findUnbalancedBracketError(code) { + return scanDartSource(String(code ?? "")).error; +} + +/** + * Whether a character offset falls inside any recorded comment or string span. + * @param {number} offset - Character offset into the scanned source + * @param {Array<{start: number, end: number}>} ranges - Comment/string spans + * @returns {boolean} True when the offset lies inside a span + */ +function offsetIsInsideCommentOrString(offset, ranges) { + return ranges.some(({ start, end }) => offset >= start && offset < end); +} diff --git a/src/flutterFlowCodeSanitizer.test.js b/src/flutterFlowCodeSanitizer.test.js new file mode 100644 index 0000000..a18d73b --- /dev/null +++ b/src/flutterFlowCodeSanitizer.test.js @@ -0,0 +1,408 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + expectedWidgetClassFromFileName, + findUnbalancedBracketError, + getDeclaredWidgetClasses, + sanitizeGeneratedDart, + widgetFileNameForClass, +} from "./flutterFlowCodeSanitizer.js"; + +const SIMPLE_WIDGET = [ + "class LiquidGlassOrbs extends StatefulWidget {", + " const LiquidGlassOrbs({super.key});", + " @override", + " State createState() => _LiquidGlassOrbsState();", + "}", +].join("\n"); + +test("sanitizeGeneratedDart leaves plain Dart untouched apart from edge padding", () => { + assert.equal(sanitizeGeneratedDart(`\n\n${SIMPLE_WIDGET}\n\n`), SIMPLE_WIDGET); +}); + +test("sanitizeGeneratedDart strips dart-fenced responses", () => { + assert.equal( + sanitizeGeneratedDart("```dart\n" + SIMPLE_WIDGET + "\n```"), + SIMPLE_WIDGET, + ); +}); + +test("sanitizeGeneratedDart strips bare fences and surrounding prose", () => { + const raw = [ + "Here is your widget:", + "", + "```", + SIMPLE_WIDGET, + "```", + "Let me know if you need changes!", + ].join("\n"); + + assert.equal(sanitizeGeneratedDart(raw), SIMPLE_WIDGET); +}); + +test("sanitizeGeneratedDart drops prose between multi-block responses", () => { + // STU-148: the previous sanitizer removed only the fence lines and kept + // whatever explanatory text sat between the blocks, so the committed file + // still failed FlutterFlow's formatter. + const raw = [ + "```dart", + "class A extends StatelessWidget {}", + "```", + "And another:", + "```dart", + "class B extends StatelessWidget {}", + "```", + ].join("\n"); + const result = sanitizeGeneratedDart(raw); + + assert.equal(result.includes("```"), false); + assert.equal(result.includes("And another"), false); + assert.match(result, /class A extends/); + assert.match(result, /class B extends/); +}); + +test("STU-147: fences inside triple-quoted strings survive as literal content", () => { + // A doc string whose example shows markdown fences must not be mistaken for + // real delimiters: pairing those lines used to slice valid Dart apart. + const dartWithFenceDoc = [ + "class FenceDoc extends StatelessWidget {", + " static const usage = '''", + "```dart", + "FenceDoc()", + "```", + "''';", + "}", + ].join("\n"); + const raw = [ + "Here is your widget:", + "", + "```dart", + dartWithFenceDoc, + "```", + ].join("\n"); + + assert.equal(sanitizeGeneratedDart(raw), dartWithFenceDoc); +}); + +test("STU-147: fences inside block comments survive as literal content", () => { + const dartWithCommentedFences = [ + "/* Generated snippet notes:", + "```json", + '{"name": "demo"}', + "```", + "*/", + "class Demo extends StatelessWidget {}", + ].join("\n"); + const raw = [ + "```dart", + dartWithCommentedFences, + "```", + "Hope that helps!", + ].join("\n"); + + assert.equal(sanitizeGeneratedDart(raw), dartWithCommentedFences); +}); + +test("sanitizeGeneratedDart drops content after an unclosed trailing fence", () => { + // A response cut off mid-block cannot be valid Dart; committing its tail + // would only move the failure to FlutterFlow's formatter. + const raw = [ + "```dart", + SIMPLE_WIDGET, + "```", + "Second part:", + "```dart", + "class Broken extends Stateless", + ].join("\n"); + const result = sanitizeGeneratedDart(raw); + + assert.equal(result, SIMPLE_WIDGET); +}); + +test("sanitizeGeneratedDart keeps the code side of a single truncated fence", () => { + assert.equal(sanitizeGeneratedDart("```\n" + SIMPLE_WIDGET), SIMPLE_WIDGET); + assert.equal(sanitizeGeneratedDart(SIMPLE_WIDGET + "\n```"), SIMPLE_WIDGET); +}); + +test("sanitizeGeneratedDart strips a BOM", () => { + assert.equal(sanitizeGeneratedDart("\uFEFF" + SIMPLE_WIDGET), SIMPLE_WIDGET); +}); + +test("sanitizeGeneratedDart returns empty for empty or blank input", () => { + assert.equal(sanitizeGeneratedDart(""), ""); + assert.equal(sanitizeGeneratedDart(" \n\t "), ""); + assert.equal(sanitizeGeneratedDart(null), ""); + assert.equal(sanitizeGeneratedDart(undefined), ""); +}); + +test("getDeclaredWidgetClasses finds public Stateless and Stateful widgets in order", () => { + const code = [ + "class First extends StatelessWidget {}", + "class _Private extends StatelessWidget {}", + "class NotAWidget extends Object {}", + "class Second extends StatefulWidget {}", + ].join("\n"); + + assert.deepEqual(getDeclaredWidgetClasses(code), ["First", "Second"]); +}); + +test("getDeclaredWidgetClasses accepts transitive Widget superclasses", () => { + const code = "class Consumer extends ConsumerStatefulWidget {}"; + + assert.deepEqual(getDeclaredWidgetClasses(code), ["Consumer"]); +}); + +test("getDeclaredWidgetClasses ignores class-shaped prose in comments and strings", () => { + const code = [ + "// class Fake extends StatelessWidget should not count.", + "final hint = 'class FakeToo extends StatefulWidget';", + "class Real extends StatelessWidget {}", + ].join("\n"); + + assert.deepEqual(getDeclaredWidgetClasses(code), ["Real"]); +}); + +test("findUnbalancedBracketError accepts healthy widget code", () => { + const code = [ + "class W extends StatelessWidget {", + " // braces } in a comment { don't count", + " final label = 'text with ) and (';", + " @override", + " Widget build(BuildContext context) {", + " return Text('${user['name']}: {literal}');", + " }", + "}", + ].join("\n"); + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("findUnbalancedBracketError reports the line of an unclosed bracket", () => { + const code = "\n{\n x();\n"; + + const error = findUnbalancedBracketError(code); + assert.match(error, /"\{" opened on line 2 is never closed/); +}); + +test("findUnbalancedBracketError reports an extra closer", () => { + const error = findUnbalancedBracketError("void a() {}\n}"); + + assert.match(error, /line 2.*unexpected "\}"/); +}); + +test("findUnbalancedBracketError reports mismatched pairs precisely", () => { + const error = findUnbalancedBracketError("void a() {\n]"); + + assert.match(error, /"\]" closes nothing - "\{" opened on line 1/); +}); + +test("findUnbalancedBracketError ignores brackets inside triple-quoted strings", () => { + const code = [ + "/// Docs:", + 'const doc = """', + "unclosed { [ ( stuff", + '""";', + "void main() {}", + ].join("\n"); + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("findUnbalancedBracketError reports an unterminated triple-quoted string", () => { + const error = findUnbalancedBracketError("const doc = '''\nnever ended {"); + + assert.match(error, /unclosed triple-quoted string/); +}); + +test("STU-148: a runaway quote fails the gate instead of self-healing", () => { + // A single-quoted string can never legally span lines. The scan still ends + // the string at the newline so later brackets attribute correctly, but it + // must surface the break through the gate - silently healing let malformed + // source reach FlutterFlow and fail with an opaque formatter rejection. + const error = findUnbalancedBracketError("final x = 'oops;\nvoid main() {}"); + + assert.match(error, /line 1: string starting on line 1 is never closed/); +}); + +test("STU-148: unterminated ordinary string followed by balanced code errors naming its line", () => { + // The Greptile P1 scenario: "abc on one line, healthy code after - the + // balanced remainder used to hide the broken string from the gate. + const code = [ + "class Broken extends StatelessWidget {", + ' final label = "abc', + " void f() {}", + "}", + ].join("\n"); + + const error = findUnbalancedBracketError(code); + assert.match(error, /string starting on line 2 is never closed/); +}); + +test("STU-148: multi-line triple-quoted strings stay legal while open", () => { + const code = [ + "final doc = '''", + "line one with ``` fences and { brackets [", + "line two keeps going", + "''';", + "void main() {}", + ].join("\n"); + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("STU-148: an unterminated triple-quoted string names its opening line", () => { + // The old message reported the live line counter at EOF instead of where + // the string actually opened. + const code = "var s = 'fine';\n\nvar t = '''\nnever closed"; + const error = findUnbalancedBracketError(code); + + assert.match(error, /unclosed triple-quoted string starting on line 3 was never closed/); +}); + +test("STU-147: nested block comments stay protected until the real close", () => { + // Dart nests block comments: the inner */ must not terminate the outer + // comment, or every later line-leading ``` inside the still-open region is + // misread as a markdown fence and the source gets dropped/rearranged. + const nestedCommentDart = [ + "/* outer doc /* inner ``` example */", + "still-open outer comment", + "```dart", + "FenceDoc()", + "```", + "*/", + "class NestedCommentDoc extends StatelessWidget {}", + ].join("\n"); + + // Byte-for-byte survival: no real fences exist, nothing may be stripped. + assert.equal(sanitizeGeneratedDart(nestedCommentDart), nestedCommentDart); + assert.equal(findUnbalancedBracketError(nestedCommentDart), null); + + // Protection holds until the true close: once the outer comment really + // ends, surrounding markdown fences pair up normally around intact content. + const raw = ["```dart", nestedCommentDart, "```", "Hope that helps!"].join("\n"); + assert.equal(sanitizeGeneratedDart(raw), nestedCommentDart); +}); + +test("STU-147: an unterminated nested block comment reports its opening line", () => { + const error = findUnbalancedBracketError("void f() {}\n/* a /* b\nstill open"); + + assert.match(error, /unterminated \/\* comment starting on line 2/); +}); + +test("findUnbalancedBracketError handles nested interpolation strings", () => { + // items[0]'s brackets sit inside the ${...} interpolation of a string; the + // nested ['...'] quotes must not terminate the outer string early. + assert.equal(findUnbalancedBracketError("f('${items[0]}');"), null); + assert.equal(findUnbalancedBracketError("t('${m['k']} v');"), null); + + // A quote left open inside an interpolation is still a real defect. + const error = findUnbalancedBracketError("f('${a[');"); + assert.match(error, /unclosed string/); +}); + +test("STU-148: a raw string ending in a backslash closes at its quote", () => { + // r'\' holds one literal backslash; treating the backslash as an escape used + // to skip the closing quote and report every following bracket against it. + const code = [ + "class BackslashSplitter extends StatelessWidget {", + " static final RegExp sep = RegExp(r'\\');", + " @override", + " Widget build(BuildContext context) => const SizedBox.shrink();", + "}", + ].join("\n"); + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("STU-148: raw triple-quoted strings keep their literal backslashes", () => { + const code = "final doc = r'''a \\ b { [ (''';\nvoid main() {}"; + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("STU-148: raw strings do not interpolate so ${ is literal", () => { + // Interpolation is disabled inside raw strings; pushing an interpolation + // frame for ${ used to misattribute the braces that follow. + const code = "final s = r'\${([{';\nvoid main() {}"; + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("STU-148: uppercase R prefix marks raw strings too", () => { + const code = "final sep = RegExp(R'\\');\nvoid main() {}"; + + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("escaped backslashes in normal strings still close correctly", () => { + // 'a\\' is a complete non-raw string holding one backslash; the escape must + // still be honored outside raw mode. + assert.equal(findUnbalancedBracketError("final x = 'a\\\\';\nvoid f() {}"), null); + + // ...and a genuinely unterminated non-raw string is still reported. + const error = findUnbalancedBracketError("final x = 'a\\;"); + assert.match(error, /unclosed string/); +}); + +test("widget file naming round-trips through FlutterFlow's naive snake_case", () => { + assert.equal(widgetFileNameForClass("LiquidGlassOrbs"), "liquid_glass_orbs.dart"); + assert.equal(expectedWidgetClassFromFileName("liquid_glass_orbs.dart"), "LiquidGlassOrbs"); + + // Acronyms: FF's naive stem puts an underscore before EVERY capital, so the + // inverse must rebuild "QAReport" from "q_a_report". + assert.equal(widgetFileNameForClass("QAReport"), "q_a_report.dart"); + assert.equal(expectedWidgetClassFromFileName("q_a_report.dart"), "QAReport"); +}); + +test("STU-147 scenario: fenced response with display-name artifact resolves cleanly", () => { + // The reported failure: LLM output wrapped in fences, artifact named + // "Liquid Glass Orbs" (display form), class declared as LiquidGlassOrbs. + const generated = [ + "```dart", + SIMPLE_WIDGET, + "```", + ].join("\n"); + const artifactName = "Liquid Glass Orbs"; + + const code = sanitizeGeneratedDart(generated); + const [declared] = getDeclaredWidgetClasses(code); + const fileName = widgetFileNameForClass(declared); + + assert.equal(declared, "LiquidGlassOrbs"); + assert.equal(fileName, "liquid_glass_orbs.dart"); + // The committed name is exactly what FF derives from its own side. + assert.equal(expectedWidgetClassFromFileName(fileName), declared); + assert.equal(findUnbalancedBracketError(code), null); +}); + +test("STU-148: prose tokens before a later block cannot hide that block", () => { + // An unmatched /* in the prose used to extend a comment range to EOF when + // the raw response was scanned as Dart, classifying the second block's + // fences as comment content and silently dropping it. + const response = [ + "Here is a note with a stray opener: /* not really a comment", + "", + "```dart", + "class First {}", + "```", + "And another note with a stray quote: \"", + "", + "```dart", + "class Second {}", + "```", + ].join("\n"); + const out = sanitizeGeneratedDart(response); + assert.ok(out.includes("class First {}"), "first block must survive"); + assert.ok(out.includes("class Second {}"), "second block must survive"); + assert.ok(!out.includes("stray"), "prose must be dropped"); +}); + +test("STU-148: dollar-prefixed raw strings inside interpolation pass the gate", () => { + // `${r'...'}` sequences used to make the r-prefix look like an identifier + // tail ($ was in IDENTIFIER_TAIL), so the backslash escaped the closing + // quote and the gate reported an unclosed string on valid Dart. + const source = `var s = '\${r'x\\'}';`; + assert.equal(findUnbalancedBracketError(source), null); + const fenced = ["```dart", source, "```"].join("\n"); + assert.equal(sanitizeGeneratedDart(fenced).trim(), source); +});